Tải bản đầy đủ (.pdf) (2,096 trang)

Programming excel with VBA and NET (2006)

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (17.72 MB, 2,096 trang )

ProgrammingExcelwithVBAand.NET
BySteveSaunders,JeffWebb
...............................................
Publisher:O'Reilly
PubDate:April2006
PrintISBN-10:0-596-00766-3
PrintISBN-13:978-0-59-600766-9
Pages:1114

TableofContents|Index

WhyprogramExcel?Forsolvingcomplexcalculationsandpresentingresults,Excelis
amazinglycompletewitheveryimaginablefeaturealreadyinplace.Butprogramming
Excelisn'taboutaddingnewfeaturesasmuchasit'saboutcombiningexistingfeaturesto
solveparticularproblems.Withafewmodifications,youcantransformExcelintoataskspecificpieceofsoftwarethatwillquicklyandpreciselyserveyourneeds.Inotherwords,
Excelisanidealplatformforprobablymillionsofsmallspreadsheet-basedsoftware
solutions.

Thebestpartis,youcanprogramExcelwithnoadditionaltools.AvariantoftheVisual
Basicprogramminglanguage,VBforApplications(VBA)isbuiltintoExceltofacilitateits
useasaplatform.WithVBA,youcancreatemacrosandtemplates,manipulateuser
interfacefeaturessuchasmenusandtoolbars,andworkwithcustomuserformsordialog
boxes.VBAisrelativelyeasytouse,butifyou'veneverprogrammedbefore,Programming
ExcelwithVBAand.NETisagreatwaytolearnalotveryquickly.Ifyou'reanexperienced
ExceluseroraVisualBasicprogrammer,you'llpickupalotofvaluablenewtricks.
Developerslookingforwardto.NETdevelopmentwillalsofinddiscussionofhowtheExcel
objectmodelworkswith.NETtools,includingVisualStudioToolsforOffice(VSTO).

ThisbookteachesyouhowtouseExcelVBAbyexplainingconceptsclearlyandconcisely
inplainEnglish,andprovidesplentyofdownloadablesamplessoyoucanlearnbydoing.
You'llbeexposedtoawiderangeoftasksmostcommonlyperformedwithExcel,arranged


intochaptersaccordingtosubject,withthosesubjectscorrespondingtooneormoreExcel
objects.Withboththesamplesandimportantreferenceinformationforeachobject
includedrightinthechapters,insteadoftuckedawayinseparatesections,Programming
ExcelwithVBAand.NETcoverstheentireExcelobjectlibrary.Forthosejuststartingout,
italsolaysdownthebasicrulescommontoallprogramminglanguages.

Withthissingle-sourcereferenceandhow-toguide,you'lllearntousethecompleterange


ofExcelprogrammingtaskstosolveproblems,nomatterwhatyou'reexperiencelevel.


ProgrammingExcelwithVBAand.NET
BySteveSaunders,JeffWebb
...............................................
Publisher:O'Reilly
PubDate:April2006
PrintISBN-10:0-596-00766-3
PrintISBN-13:978-0-59-600766-9
Pages:1114

TableofContents|Index


















































ProgrammingExcelwithVBAand.NET
Preface
PartI:LearningVBA
Chapter1.BecominganExcelProgrammer
Section1.1.WhyProgram?
Section1.2.RecordandReadCode
Section1.3.ChangeRecordedCode
Section1.4.FixMisteakes
Section1.5.StartandStop
Section1.6.ViewResults
Section1.7.Where'sMyCode?
Section1.8.MacrosandSecurity
Section1.9.WriteBug-FreeCode
Section1.10.NavigateSamplesandHelp
Section1.11.WhatYou'veLearned
Chapter2.KnowingtheBasics
Section2.1.PartsofaProgram
Section2.2.ClassesandModules
Section2.3.Procedures
Section2.4.Variables

Section2.5.ConditionalStatements
Section2.6.Loops
Section2.7.Expressions
Section2.8.Exceptions




















































































Section2.9.WhatYou'veLearned
Chapter3.TasksinVisualBasic
Section3.1.TypesofTasks
Section3.2.InteractwithUsers

Section3.3.DoMath
Section3.4.WorkwithText
Section3.5.GetDatesandTimes
Section3.6.ReadandWriteFiles
Section3.7.CheckResults
Section3.8.FindTruth
Section3.9.CompareBits
Section3.10.RunOtherApplications
Section3.11.ControltheCompiler
Section3.12.NotCoveredHere
Section3.13.WhatYou'veLearned
Chapter4.UsingExcelObjects
Section4.1.ObjectsandTheirMembers
Section4.2.GetExcelObjects
Section4.3.GetObjectsfromCollections
Section4.4.AboutMeandtheActiveObject
Section4.5.FindtheRightObject
Section4.6.CommonMembers
Section4.7.RespondtoEventsinExcel
Section4.8.TheGlobalObject
Section4.9.TheWorksheetFunctionObject
Section4.10.WhatYou'veLearned
Chapter5.CreatingYourOwnObjects
Section5.1.ModulesVersusClasses
Section5.2.AddMethods
Section5.3.CreateProperties
Section5.4.DefineEnumerations
Section5.5.RaiseEvents
Section5.6.CollectObjects
Section5.7.ExposeObjects

Section5.8.DestroyObjects
Section5.9.ThingsYouCan'tDo
Section5.10.WhatYou'veLearned
Chapter6.WritingCodeforUsebyOthers
Section6.1.TypesofApplications



















































































Section6.2.TheDevelopmentProcess
Section6.3.DetermineRequirements
Section6.4.Design
Section6.5.ImplementandTest

Section6.6.Integrate
Section6.7.TestPlatforms
Section6.8.Document
Section6.9.Deploy
Section6.10.WhatYou'veLearned
Section6.11.Resources
PartII:ExcelObjects
Chapter7.ControllingExcel
Section7.1.PerformTasks
Section7.2.ControlExcelOptions
Section7.3.GetReferences
Section7.4.ApplicationMembers
Section7.5.AutoCorrectMembers
Section7.6.AutoRecoverMembers
Section7.7.ErrorCheckingMembers
Section7.8.SpellingOptionsMembers
Section7.9.WindowandWindowsMembers
Section7.10.PaneandPanesMembers
Chapter8.Opening,Saving,andSharingWorkbooks
Section8.1.Add,Open,Save,andClose
Section8.2.ShareWorkbooks
Section8.3.ProgramwithSharedWorkbooks
Section8.4.ProgramwithSharedWorkspaces
Section8.5.RespondtoActions
Section8.6.WorkbookandWorkbooksMembers
Section8.7.RecentFileandRecentFilesMembers
Chapter9.WorkingwithWorksheetsandRanges
Section9.1.WorkwithWorksheetObjects
Section9.2.WorksheetsandWorksheetMembers
Section9.3.SheetsMembers

Section9.4.WorkwithOutlines
Section9.5.OutlineMembers
Section9.6.WorkwithRanges
Section9.7.RangeMembers
Section9.8.WorkwithScenarioObjects


















































































Section9.9.ScenarioandScenariosMembers
Section9.10.Resources
Chapter10.LinkingandEmbedding
Section10.1.AddComments
Section10.2.UseHyperlinks

Section10.3.LinkandEmbedObjects
Section10.4.Speak
Section10.5.CommentandCommentsMembers
Section10.6.HyperlinkandHyperlinksMembers
Section10.7.OleObjectandOleObjectsMembers
Section10.8.OLEFormatMembers
Section10.9.SpeechMembers
Section10.10.UsedObjectsMembers
Chapter11.PrintingandPublishing
Section11.1.PrintandPreview
Section11.2.ControlPaging
Section11.3.ChangePrinterSettings
Section11.4.FilterRanges
Section11.5.SaveandDisplayViews
Section11.6.PublishtotheWeb
Section11.7.AutoFilterMembers
Section11.8.FilterandFiltersMembers
Section11.9.CustomViewandCustomViewsMembers
Section11.10.HPageBreak,HPageBreaks,VPageBreak,VPageBreaks
Members
Section11.11.PageSetupMembers
Section11.12.GraphicMembers
Section11.13.PublishObjectandPublishObjectsMembers
Section11.14.WebOptionsandDefaultWebOptionsMembers
Chapter12.LoadingandManipulatingData
Section12.1.WorkingwithQueryTableObjects
Section12.2.QueryTableandQueryTablesMembers
Section12.3.WorkingwithParameterObjects
Section12.4.ParameterMembers
Section12.5.WorkingwithADOandDAO

Section12.6.ADOObjectsandMembers
Section12.7.DAOObjectsandMembers
Section12.8.DAO.DatabaseandDAO.DatabasesMembers
Section12.9.DAO.DocumentandDAO.DocumentsMembers



















































































Section12.10.DAO.QueryDefandDAO.QueryDefsMembers
Section12.11.DAO.RecordsetandDAO.RecordsetsMembers
Chapter13.AnalyzingDatawithPivotTables
Section13.1.QuickGuidetoPivotTables
Section13.2.ProgramPivotTables

Section13.3.PivotTableandPivotTablesMembers
Section13.4.PivotCacheandPivotCachesMembers
Section13.5.PivotFieldandPivotFieldsMembers
Section13.6.CalculatedFieldsMembers
Section13.7.CalculatedItemsMembers
Section13.8.PivotCellMembers
Section13.9.PivotFormulaandPivotFormulasMembers
Section13.10.PivotItemandPivotItemsMembers
Section13.11.PivotItemListMembers
Section13.12.PivotLayoutMembers
Section13.13.CubeFieldandCubeFieldsMembers
Section13.14.CalculatedMemberandCalculatedMembersMembers
Chapter14.SharingDataUsingLists
Section14.1.UseLists
Section14.2.ListObjectandListObjectsMembers
Section14.3.ListRowandListRowsMembers
Section14.4.ListColumnandListColumnsMembers
Section14.5.ListDataFormatMembers
Section14.6.UsetheListsWebService
Section14.7.ListsWebServiceMembers
Section14.8.Resources
Chapter15.WorkingwithXML
Section15.1.UnderstandXML
Section15.2.SaveWorkbooksasXML
Section15.3.UseXMLMaps
Section15.4.ProgramwithXMLMaps
Section15.5.XmlMapandXmlMapsMembers
Section15.6.XmlDataBindingMembers
Section15.7.XmlNamespaceandXmlNamespacesMembers
Section15.8.XmlSchemaandXmlSchemasMembers

Section15.9.GetanXMLMapfromaListorRange
Section15.10.XPathMembers
Section15.11.Resources
Chapter16.Charting

















































































Section16.1.NavigateChartObjects
Section16.2.CreateChartsQuickly
Section16.3.EmbedCharts
Section16.4.CreateMoreComplexCharts
Section16.5.ChooseChartType
Section16.6.CreateComboCharts
Section16.7.AddTitlesandLabels

Section16.8.PlotaSeries
Section16.9.RespondtoChartEvents
Section16.10.ChartandChartsMembers
Section16.11.ChartObjectandChartObjectsMembers
Section16.12.ChartGroupandChartGroupsMembers
Section16.13.SeriesLinesMembers
Section16.14.AxesandAxisMembers
Section16.15.DataTableMembers
Section16.16.SeriesandSeriesCollectionMembers
Section16.17.PointandPointsMembers
Chapter17.FormattingCharts
Section17.1.FormatTitlesandLabels
Section17.2.ChangeBackgroundsandFonts
Section17.3.AddTrendlines
Section17.4.AddSeriesLinesandBars
Section17.5.ChartTitle,AxisTitle,andDisplayUnitLabelMembers
Section17.6.DataLabelandDataLabelsMembers
Section17.7.LeaderLinesMembers
Section17.8.ChartAreaMembers
Section17.9.ChartFillFormatMembers
Section17.10.ChartColorFormatMembers
Section17.11.DropLinesandHiLoLinesMembers
Section17.12.DownBarsandUpBarsMembers
Section17.13.ErrorBarsMembers
Section17.14.LegendMembers
Section17.15.LegendEntryandLegendEntriesMembers
Section17.16.LegendKeyMembers
Section17.17.GridlinesMembers
Section17.18.TickLabelsMembers
Section17.19.TrendlineandTrendlinesMembers

Section17.20.PlotAreaMembers




Section17.21.FloorMembers



Section17.22.WallsMembers













































































Section17.23.CornersMembers
Chapter18.DrawingGraphics
Section18.1.DrawinExcel
Section18.2.CreateDiagrams
Section18.3.ProgramwithDrawingObjects

Section18.4.ProgramDiagrams
Section18.5.Shape,ShapeRange,andShapesMembers
Section18.6.AdjustmentsMembers
Section18.7.CalloutFormatMembers
Section18.8.ColorFormatMembers
Section18.9.ConnectorFormatMembers
Section18.10.ControlFormatMembers
Section18.11.FillFormatMembers
Section18.12.FreeFormBuilder
Section18.13.GroupShapesMembers
Section18.14.LineFormatMembers
Section18.15.LinkFormatMembers
Section18.16.PictureFormatMembers
Section18.17.ShadowFormat
Section18.18.ShapeNodeandShapeNodesMembers
Section18.19.TextFrame
Section18.20.TextEffectFormat
Section18.21.ThreeDFormat
Chapter19.AddingMenusandToolbars
Section19.1.AboutExcelMenus
Section19.2.BuildaTop-LevelMenu
Section19.3.CreateaMenuinCode
Section19.4.BuildContextMenus
Section19.5.BuildaToolbar
Section19.6.CreateToolbarsinCode
Section19.7.CommandBarandCommandBarsMembers
Section19.8.CommandBarControlandCommandBarControlsMembers
Section19.9.CommandBarButtonMembers
Section19.10.CommandBarComboBoxMembers
Section19.11.CommandBarPopupMembers

Chapter20.BuildingDialogBoxes




Section20.1.TypesofDialogs




Section20.2.CreateData-EntryForms
Section20.3.DesignYourOwnForms








































































Section20.4.UseControlsonWorksheets
Section20.5.UserFormandFrameMembers
Section20.6.ControlandControlsMembers
Section20.7.FontMembers
Section20.8.CheckBox,OptionButton,ToggleButtonMembers
Section20.9.ComboBoxMembers
Section20.10.CommandButtonMembers
Section20.11.ImageMembers

Section20.12.LabelMembers
Section20.13.ListBoxMembers
Section20.14.MultiPageMembers
Section20.15.PageMembers
Section20.16.ScrollBarandSpinButtonMembers
Section20.17.TabStripMembers
Section20.18.TextBoxandRefEditMembers
Chapter21.SendingandReceivingWorkbooks
Section21.1.SendMail
Section21.2.WorkwithMailItems
Section21.3.CollectReviewComments
Section21.4.RouteWorkbooks
Section21.5.ReadMail
Section21.6.MsoEnvelopeMembers
Section21.7.MailItemMembers
Section21.8.RoutingSlipMembers
PartIII:ExtendingExcel
Chapter22.BuildingAdd-ins
Section22.1.TypesofAdd-ins
Section22.2.Code-OnlyAdd-ins
Section22.3.VisualAdd-ins
Section22.4.SetAdd-inProperties
Section22.5.SigntheAdd-in
Section22.6.DistributetheAdd-in
Section22.7.WorkwithAdd-insinCode
Section22.8.AddInandAddInsMembers

















































































Chapter23.IntegratingDLLsandCOM
Section23.1.UseDLLs
Section23.2.UseCOMApplications
Chapter24.GettingDatafromtheWeb
Section24.1.PerformWebQueries
Section24.2.QueryTableandQueryTablesWebQueryMembers
Section24.3.UseWebServices
Section24.4.Resources
Chapter25.ProgrammingExcelwith.NET
Section25.1.ApproachestoWorkingwith.NET
Section25.2.Create.NETComponentsforExcel
Section25.3.Use.NETComponentsinExcel
Section25.4.UseExcelasaComponentin.NET
Section25.5.CreateExcelApplicationsin.NET
Section25.6.Resources
Chapter26.ExploringSecurityinDepth

Section26.1.SecurityLayers
Section26.2.UnderstandWindowsSecurity
Section26.3.Password-ProtectandEncryptWorkbooks
Section26.4.ProgramwithPasswordsandEncryption
Section26.5.WorkbookPasswordandEncryptionMembers
Section26.6.ExcelPasswordSecurity
Section26.7.ProtectItemsinaWorkbook
Section26.8.ProgramwithProtection
Section26.9.WorkbookProtectionMembers
Section26.10.WorksheetProtectionMembers
Section26.11.ChartProtectionMembers
Section26.12.ProtectionMembers
Section26.13.AllowEditRangeandAllowEditRangesMembers
Section26.14.UserAccessandUserAccessListMembers
Section26.15.SetWorkbookPermissions
Section26.16.ProgramwithPermissions
Section26.17.PermissionandUserPermissionMembers
Section26.18.AddDigitalSignatures
Section26.19.SetMacroSecurity
Section26.20.SetActiveXControlSecurity
Section26.21.DistributeSecuritySettings
Section26.22.UsingtheAnti-VirusAPI























Section26.23.CommonTasks
Section26.24.Resources
PartIV:Appendixes
AppendixA.ReferenceTables
SectionA.1.DialogsCollectionConstants
SectionA.2.CommonProgrammaticIDs
AppendixB.VersionCompatibility
SectionB.1.SummaryofVersionChanges
SectionB.2.MacintoshCompatibility
AbouttheAuthor
Colophon
Index


ProgrammingExcelwithVBAand.NET
byJeffWebbandSteveSaunders

Copyright©2006O'ReillyMedia,Inc.Allrightsreserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,or
salespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles(safari.oreilly.com).Formoreinformation,contact
ourcorporate/institutionalsalesdepartment:(800)998-9938or

Editor:

SimonSt.Laurent,JohnOsborn

ProductionEditor:

SandersKleinfeld

Copyeditor:

NormaEmory

Indexer:

EllenTroutman-Zaig

CoverDesigner:

KarenMontgomery

InteriorDesigner:


DavidFutato

Illustrators:

RobertRomano,JessamynRead,andLesleyBorash

PrintingHistory:




April2006:

FirstEdition.

NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
ProgrammingExcelwithVBAand.NET,theimageofashoveler
duck,andrelatedtradedressaretrademarksofO'ReillyMedia,
Inc.
Microsoft,the.NETlogo,VisualBasic.NET,VisualStudio.NET,
ADO.NET,Excel,Windows,andWindows2000areregistered
trademarksofMicrosoftCorporation.
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andO'ReillyMedia,Inc.
wasawareofatrademarkclaim,thedesignationshavebeen
printedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis

book,thepublisherandauthorsassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.
ISBN:0-596-00766-3
[M]


Preface
IwasluckyenoughtobeatMicrosoftwhenVisualBasicwas
addedtoExcel.IhadjustwrappedupworkingonOLE
AutomationthetechnologyusedtomakeExcelobjects
programmableandIrememberthatmeetingswiththeExcel
groupwere,attimes,difficult.WhyshouldapremierMicrosoft
productlikeExcelputsomucheffortintoaddingalow-profit
itemlikeVisualBasicwhenitalreadyhadamacrolanguage?
"BecauseBillGsaidso"takesyouonlysofar,evenatMicrosoft.
Thefactsarethatprogrammabilitydoesn'tsellproductsthe
waysomeotherwhizbangfeaturemight,itaddsriskto
deliveringtheproductbug-freeandontime,and(wefound
out)itposesasecurityhazard.
Whatprogrammabilitydoesdoismakeyourproductaplatform
forothers.Today,Excelisthefoundationforprobablymillions
ofsmallspreadsheet-basedsoftwaresolutionsandisusedby
certainlythousandsofverylargeandsophisticatedapplications.
Thatsellsproducts.
ItalsomakestheskillofprogrammingExcelextremely
valuable.ThecommunityofExcelprogrammersislarge,
knowledgeable,and(Ihope)wellpaid.

LearnbyDoing

TherearealwaysnewExcelprogrammersjoiningourranks.If
youarenewtoExcelornewtoprogramming,Iwelcomeyou.
Thisbookisn'tabeginnerseries,butifyoureadtheearly
chaptersandaremotivated,Ithinkyou'llfindthisbookagreat
waytolearnalotveryquickly.
IfyouareanexperiencedExceluseroraVisualBasic


programmer,howdy!I'vegotalottoshowyou.

Don'tForceIt
Ifyougetstuck,thereareanumberofwaystoresumeyour
progress:
Tryturningonmacrorecording(Tools Macros Record
aNewMacro),performingthetaskinExcel,andthen
turningoffrecordingandexaminingthecodethatExcel
generates.
SearchMSDN(toseeif
Microsofthasaddressedyourproblem.
Searchnewsgroups(to
seeifsomeoneelsehassolvedyourproblem.
Andofcourse,youcanalwayscheck
toseeifI'vesolvedtheproblem!
Ifsomethingstillseemstoodifficult,examineyourapproach.I
generallygofishinginthatsituationandcomebacktothe
problemlater.Ifyoudon'tlivesomewherewithgoodfishing,I
guessyou'rejuststuck.

ExcelVersions
ThisbookwasdevelopedwithExcel2003ProfessionalEdition

andisdesignedtobecompatiblewithExcel2000andlater.Ifa
featureisnotavailableinExcel2000,Imakeanefforttonote
that,butifyouaredevelopingforaspecificversionofExcel,
pleasecheckAppendixBforspecificversioncompatibilityand
readChapter6forinformationondevelopingdesign


requirementsandtestingforcompatibility.
Ifyouaredevelopingwith.NET,Istronglyrecommendthatyou
targetExcel2003orlater.Thecodeshowninthisbookis
writtenintheVisualBasicApplicationsEdition,butparallel.NET
samplesareprovidedonline(seethenextsection).

GettheSamples
Thesamplesforthisbookareavailableat
.You'llneedthem,sogogetthem
now.TheexamplescomeinaWindowscompressedfolder(.zip)
thatyou'llneedtoexpandonyourcomputer.
Thesamplesareorganizedbychapter,andeachchapterhas
parallelsampleswrittenasVisualStudio.NETprojects.Each
chapterusesonemainworkbook(ch01.xls,ch02.xls,etc.)asa
startingpointtoprovideinstructionsandnavigation.

What'sinThisBook
Chaptersinthisbookareorganizedbyprogrammingtask.I
coverthemostcommontasksforeachsubjectwithinachapter.
SubjectsusuallycorrespondtooneormoreExcelobjects,andI
includeimportantreferenceinformationforthoseobjectswithin
eachchapter,ratherthanpushingthatinformationtotheback
ofthebook.


Idon'texpectthisbookwillbeyouronlyresource,andItrynotto
duplicatestuffyoualreadyhave(likeonlineHelp),soIincludecrossreferencestoothersources.I'vealsoincludedthoseresourcesas
hyperlinksinthesampleworkbooks(seetheResourcessheet).Mostly,
thoselinksdealwithmuchmorespecificissuesrelatedtothetopic,but
theyalsoincludelinkstotoolkitsandothersoftwareyoumayneed.


Hereisabriefoverviewofeachchapter:
Chapter1,BecominganExcelProgrammer,ismeantfor
thosenewtoExcelprogramming.Itcovershowtorecord,
change,run,anddebugcodeintheExcelVisualBasic
Editor.ExperiencedExcelprogrammerscanskipthis
chapter,althoughtheymaywanttoreadthesection"Write
Bug-FreeCode."
Chapter2,KnowingtheBasics,explainsthepartsofa
program:classes,modules,procedures,properties,events,
variables,constants,andalltheotherprogramming
fundamentals.Experiencedprogrammersmightwantto
skiprightto"Objects"and"Exceptions"inthischapter.
Chapter3,TasksinVisualBasic,teacheshowtousecore
VisualBasicfeaturestodisplaysimpledialogboxes,
performcalculations,workwithtext,readandwritefiles,
checkresults,andrunotherapplications.Experienced
readerswillbemostinterestedinthesection"Compare
Bits."
Chapter4,UsingExcelObjects,showsyouhowobjects
workandhelpsyoufindtherightobjectforanygiventask
inExcel.Theobjectdiagramsinthischapterarearoadmap
tothemanyobjectsthatExcelprovides.Thisisthefirst

placetolookwhensearchingfortheappropriateobjectfor
aparticulartask.
Chapter5,CreatingYourOwnObjects,goesin-depthabout
object-orientedprogramming(OOP).You'lllearnhowto
constructclasses,methods,properties,collections,and
events.Ialsoexplainwhyitisimportanttodestroyyour


creationsonceyouaredoneusingthem.
Chapter6,WritingCodeforUsebyOthers,isabouttaking
yourskillstothenextlevel.Icoverthetypesofapplications
youcancreate,explainthedevelopmentprocess,andshow
howtoproperlydeployacompletedapplication.
Chapter7,ControllingExcel,beginsthetask-specificpartof
thisbook.Itshowshowtousethetop-levelApplication
objecttoopenandcloseExcelwindows,displaydialogs,
andgetreferencestootherExcelobjects.
Chapter8,Opening,Saving,andSharingWorkbooks,
teachesyouhowtoworkwithExceldocumentfiles
(workbooks).Asabonus,IcoverhowtoworkwithXMLand
useSharePointworkspacesfromExcel.
Chapter9,WorkingwithWorksheetsandRanges,covers
thetwomost-usedobjectsinExcel.Almosteverythingyou
doinExcelinvolvesworksheetsandrangesinsomeway.
Chapter10,LinkingandEmbedding,discusseshowtoadd
comments,hyperlinks,andobjectsfromotherapplications
toaworksheet.IalsoshowhowtomakeExcelspeakout
loudweirdbuttrue!
Chapter11,PrintingandPublishing,isaboutsendingoutput
totheprinterortheWeb.Ishowhowtocontrolpaging,

changeprintersettings,filteroutput,previewresults,and
publishrangestoawebpage.
Chapter12,LoadingandManipulatingData,isallabout
connectingtodatabases.IshowhowtouseQueryTables
andusetheADOandDAOobjectmodels.


Chapter13,AnalyzingDatawithPivotTables,showshowto
programwithoneofExcel'smostcelebratedfeatures.I
showhowtoreorganizedatafromawidevarietyofdata
sources,includingOLAPdatacubes.
Chapter14,SharingDataUsingLists,goesintodetailon
oneofExcel'snewestfeatures:datalists.Ishowhowto
usethemtosort,filter,andevensharelistsacrossthe
networkthroughSharePoint.
Chapter15,WorkingwithXML,isalsoaground-breaker,by
showinghowtoconvertXMLdatafilesintoExcelworkbooks
andviceversa.IprovideabriefintroductiontoXMLand
XSL,thendivetotheheartofhowtoimportXMLdatato
liststhroughXMLmaps.
Chapter16,Charting,covershowtocreatedifferenttypes
ofchartsandcontrolthemainpartsofachart.Chartingisa
largeandcomplextopicinExcel,soIalsoincludearoad
maptothechartobjects.
Chapter17,FormattingCharts,explainshowtocontrolthe
fonts,backgrounds,and3-Deffectsusedonachart.Itis
thecompaniontoChapter16.
Chapter18,DrawingGraphics,isreallyjustforfun.Excel's
drawingtoolsletyoucreatediagramsandothergraphics
fromdata,butyouneedtoknowaboutacouplegotchas.I

coverthosehere.
Chapter19,AddingMenusandToolbars,helpsyouhook
yourapplicationintotheExceluserinterface.Ialsoshow
howtodistributethemenusandtoolbarswithyourcode.
Chapter20,BuildingDialogBoxes,isaboutcreatingdata


entryandUserFormstogetinputordisplayresultsto
users.IcoverthecontrolsincludedintheMicrosoftForms
librarieshere.
Chapter21,SendingandReceivingWorkbooks,showsall
thewaystosendemailfromExcel.
Chapter22,BuildingAdd-Ins,covershowtocreateand
distributeyourprogramasanExcelAdd-In.Thischapter
beginstheadvancedprogrammingmaterial.
Chapter23,IntegratingDLLsandCOM,showshowtouse
codefromWindowsitselforotherapplicationswithinyour
Excelprograms.
Chapter24,GettingDataFromtheWeb,explainshowto
scrapedatafromwebpagesusingwebqueriesandhowto
executewebservicestoperformtasksremotelyacrossa
network.
Chapter25,ProgrammingExcelwith.NET,teacheshowto
use.NETcodefromwithinExcel,useExcelcodefrom.NET,
orintegratebetweenExceland.NETusingVisualStudio
ToolsforOffice(VSTO).
Chapter26,ExploringSecurityinDepth,discussesWindows
security,encryption,passwords,protection,andInformation
RightsManagement(IRM)withinExcel.Ialsoshowhow
well(orpoorly)certainsecurityfeaturesperform.


FontConventions
Thisbookfollowscertainconventionsforfontusage.
Understandingtheseconventionsupfrontmakesiteasierto
usethisbook.


Italicisusedfor:
Pathnames,filenames,programnames,compilers,options,
andcommands
Newtermswheretheyaredefined
Internetaddresses,suchasdomainnamesandURLs
Constantwidthisusedfor:

AnythingthatappearsliterallyinaVisualBasicprogram,
includingkeywords,datatypes,constants,methodnames,
variables,classnames,andinterfacenames
Commandlinesandoptionsthatshouldbetypedverbatim
onthescreen
Allcodelistings
HTMLdocuments,tags,andattributes
Constantwidthitalicisusedfor:

Generalplaceholdersthatindicatethatanitemisreplaced
bysomeactualvalueinyourownprogram
Constantwidthboldisusedfor:

Textincodeexamplesthatistypedbytheuser
Highlightingcodeadditionsorchangesthatshouldbenoted
bythereader



Thisicondesignatesanote,whichisanimportantasidetothenearby
text.

Thisicondesignatesawarningrelatingtothenearbytext.

SyntaxConventions
Booksaboutcomputerlanguagesrequireawaytoexpressthe
kindsofinformationyouneedtoprovideononeormorelines
asyoutype.Thatiscalledthesyntaxofthelanguageand
Backus-NaurForm(BNF)istheformatusedinthisbookand
mostothers.InBNFnotation,thefollowingconventionsapply:
Example

Meaning

Keyword

Roman(non-italic)wordsarekeywordsthatmustbetypedexactlyas
shown.

Argument

Italicsindicateanitemyoumustprovide,suchasanobjectvariablea
setting.

[]

Squarebracketsindicateanoptionalitem.


choice1|choice2 Astraightbarindicatesachoicebetweentwoormoreitems.
{choice1|
choice2}

Bracesindicatethatyoumustchooseoneoftheindicatedsettings.

[choice1|
choice2]

Squarebracketsindicatethatthechoiceisoptional.


Theseconventionsareusedinheadingswithinthereference
sectionsofthisbookandalsowithinthetextsometimes.You'll
alsoseethemintheonlinehelpfromMicrosoft.

UsingCodeExamples
Thisbookisheretohelpyougetyourjobdone.Ingeneral,you
mayusethecodeinthisbookinyourprogramsand
documentation.Youdonotneedtocontactusforpermission
unlessyou'rereproducingasignificantportionofthecode.For
example,writingaprogramthatusesseveralchunksofcode
fromthisbookdoesnotrequirepermission.Sellingor
distributingaCD-ROMofexamplesfromO'Reillybooksdoes
requirepermission.Answeringaquestionbycitingthisbook
andquotingexamplecodedoesnotrequirepermission.
Incorporatingasignificantamountofexamplecodefromthis
bookintoyourproduct'sdocumentationdoesrequire
permission.

Weappreciate,butdonotrequire,attribution.Anattribution
usuallyincludesthetitle,author,publisher,andISBN.For
example:"ProgrammingExcelwithVBAand.NET,byJeffWebb
andSteveSaunders.Copyright2006O'ReillyMedia,Inc.,0596-00766-3."
Ifyoufeelyouruseofcodeexamplesfallsoutsidefairuseor
thepermissiongivenabove,feelfreetocontactusat


Safari®Enabled


WhenyouseeaSafari®Enabledicononthecoverof
yourfavoritetechnologybook,thatmeansthebookisavailable
onlinethroughtheO'ReillyNetworkSafariBookshelf.
Safarioffersasolutionthat'sbetterthane-books.It'savirtual
librarythatletsyoueasilysearchthousandsoftoptechbooks,
cutandpastecodesamples,downloadchapters,andfindquick
answerswhenyouneedthemostaccurate,currentinformation.
Tryitforfreeat.

HowtoContactUs
Pleaseaddresscommentsandquestionsconcerningthisbookto
thepublisher:
O'ReillyMedia,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472
(800)998-9938(intheUnitedStatesorCanada)
(707)829-0515(internationalorlocal)
(707)829-0104(fax)
Wehaveawebpageforthisbook,wherewelisterrata,

examples,oranyadditionalinformation.Youcanaccessthis
pageat:
/>Tocommentorasktechnicalquestionsaboutthisbook,send
emailto:

Formoreinformationaboutourbooks,conferences,Resource
Centers,andtheO'ReillyNetwork,seeourwebsiteat:


×