About the Authors vDifferences Between Access and Excel 4 Different Types of Excel Spreadsheets 4The Excel Worksheet in Report Format 4The Excel Worksheet in Flat File Format 5The Excel
Trang 2Michael Alexander and
Geoffrey Clark
with Office 2007
Trang 301_104880 ffirs.qxp 3/22/07 10:47 PM Page iv
Trang 4Michael Alexander and
Geoffrey Clark
with Office 2007
Trang 5Microsoft ® Excel ® & Access™ Integration with Office 2007
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com
Copyright © 2007 by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada
ISBN: 978-0-470-10488-0 Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
No part of this publication may be reproduced, stored in a retrieval system or transmitted
in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copy- right Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600 Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty:The publisher and the author make no sentations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fit- ness for a particular purpose No warranty may be created or extended by sales or promo- tional materials The advice and strategies contained herein may not be suitable for every situation This work is sold with the understanding that the publisher is not engaged in ren- dering legal, accounting, or other professional services If professional assistance is required, the services of a competent professional person should be sought Neither the publisher nor the author shall be liable for damages arising herefrom The fact that an orga- nization or Website is referred to in this work as a citation and/or a potential source of fur- ther information does not mean that the author or the publisher endorses the information the organization or Website may provide or recommendations it may make Further, read- ers should be aware that Internet Websites listed in this work may have changed or disap- peared between when this work was written and when it is read.
repre-For general information on our other products and services or to obtain technical support, please contact our Customer Care Department within the U.S at (800) 762-2974, outside the U.S at (317) 572-3993 or fax (317) 572-4002.
Library of Congress Control Number: 2007007062 Trademarks:Wiley, the Wiley logo, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc and/or its affiliates, in the United States and other countries, and may not be used without written permission Microsoft, Excel, and Access are trademarks or registered trademarks of Microsoft Corporation in the United States and/or other countries All other trademarks are the property of their respective owners Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book Wiley also publishes its books in a variety of electronic formats Some content that appears
in print may not be available in electronic books.
01_104880 ffirs.qxp 3/22/07 10:47 PM Page ii
Trang 6Mike Alexander For Mary, Ethan and Emma
Geoffrey Clark For FairBear and LittlestBear, the fairest and littlest of all bears in the land
Trang 701_104880 ffirs.qxp 3/22/07 10:47 PM Page iv
Trang 8Mike Alexander is a Microsoft Certified Applications Developer (MCAD)with over 14 years experience developing Office solutions for a wide array ofCompanies and industries He currently lives in Frisco, Texas, where he works
as a Senior Program Manager for a top technology firm He is the author ofseveral books on data analysis using Excel and Access, and he is the principalbehind DataPigTechnologies.com, a site that offers free tutorials on Exceland Access
Geoff Clark holds an MBA from Duke University’s Fuqua School of Businesswhere he graduated as a Fuqua Scholar in 2000 After business school, Geoffjoined McKinsey & Company in Charlotte, NC, as an associate managementconsultant It was at McKinsey & Company where Geoff began applyingadvanced Microsoft Excel and Access techniques to aid clients in analyticalproblem solving and fact-based decision making After his stint in manage-ment consulting, Geoff served as director of marketing analytics with a $700million environmental services firm Currently, he is a manager at a majortechnology outsourcing company and develops office applications to enableenterprise-wide metrics and change initiatives Geoff lives in Plano, TX, withhis wife and son
About the Authors
v
Trang 901_104880 ffirs.qxp 3/22/07 10:47 PM Page vi
Trang 10Quality Control Technicians
John GreenoughBrian H Walls
Proofreading and Indexing
Trang 1101_104880 ffirs.qxp 3/22/07 10:47 PM Page viii
Trang 12About the Authors v
Differences Between Access and Excel 4
Different Types of Excel Spreadsheets 4The Excel Worksheet in Report Format 4The Excel Worksheet in Flat File Format 5The Excel Worksheet in Indexed List Format 6The Access Table 8The Table in the Datasheet View 8The Table in the Design View 8Different Types of Data 9Table and Field Naming Conventions 11
Bringing Your Excel Data into Access 11
Importing a Worksheet into a New Table 11Linking an Excel Worksheet to Access 18Appending an Excel Worksheet to an Existing Table 22Potential Errors When Using the Append Import Wizard 23
Chapter 2: Analyzing Excel Data with Access Queries 27
Introduction to Access Queries 27
Creating Your First Select Query 28Sorting Query Results 31Filtering Query Results 32
Contents
ix
Trang 13Querying Multiple Tables 33Understanding the Concept of Relational Databases 34Creating a Query that Joins Two Tables 35Using Operators to Further Refine Your Queries 37Exporting Query Results 40
Using Aggregate Queries 42
Aggregate Query Basics 42About Aggregate Functions 44
Sum, Avg, Count, StDev, Var 46Min, Max, First, Last 47Expression, Where 47
Using Calculations in Your Analysis 50
Common Calculation Scenarios 50Using Constants in Calculations 51Using Fields in Calculations 51Using the Results of Aggregation in Calculations 52Using the Results of One Calculation as an Expression
Performing Simple Date Calculations 53
Leveraging Access Query Wizards to Solve Common Excel Problems 55
The Find Duplicates Query Wizard 55The Find UnMatched Query Wizard 58Crosstab Queries 62
Chapter 3: Sprucing Up Excel Data with Access Reports 69
A Closer Look at the Access Report 69
Creating Your First Report 69Viewing Your Report 71
Sorting and Totaling 80
Customizing Reports with Formatting 83
Page Layout Techniques 83Solving Page Break Issues 83Multi-Column Report Layout Example 84Formatting Techniques 90Formatting to Make Reports More Readable 91Formatting to Highlight Specific Results 93
x Contents
02_104880 ftoc.qxp 3/22/07 10:47 PM Page x
Trang 14Creating an Individualized Customer Letter 95
Developing the Report Data Feed 95Initial Design of the Report 96Adding Finishing Touches for a Professional Look 101
Chapter 4: Using PivotTables and PivotCharts in Access 103
Working with PivotTables in Access 103
PivotTables in Access? 104The Anatomy of a PivotTable 105The Totals and Detail Area 105The Row Area 106The Column Area 106The Filter Area 107Creating a Basic PivotTable 107Creating an Advanced PivotTable with Details 111Saving Your PivotTable 113Sending Your Access PivotTable to Excel 114PivotTable Options 115Expanding and Collapsing Fields 116Changing Field Captions 116Sorting Data 117Grouping Data 117Using Date Groupings 120Filtering for Top and Bottom Records 121Adding a Calculated Total 122
Working with PivotCharts in Access 125
The Data Area 125The Series Area 125The Category Area 127The Filter Area 127Creating a Basic PivotChart 128Formatting Your PivotChart 130
Different Options for Importing Access Data 135
The Drag-and-Drop Method 136Exporting the Data from Access 137Using the Get External Data Menu 140Using Microsoft Query 143
Introduction to Microsoft Query 143
Using the Microsoft Query Wizard 143Starting the Query Wizard 144Choosing and Modifying Your Data with the Query Wizard 145Going Beyond the Wizard in Microsoft Query 156Introduction to the Microsoft Query Interface 157Using Microsoft Query to Import Data 159
Contents xi
Trang 15Advanced Use of Microsoft Query 164
Modifying SQL to Create Custom Fields 167
A Very Brief Primer on SQL 167Creating the Field 167Adding User Defined Parameters in Microsoft Query 170
A Simple User-Defined Parameter 171Advanced Example of User-Defined Parameter 172
Limitations of Microsoft Query 178
The Microsoft Query Wizard 178Microsoft Query 178
Chapter 6: Leveraging Macros in Excel and Access 181
What Is a Macro? 181
A General Definition 181Why Use a Macro? 182Creating User Friendly Interfaces 182Automating Repetitive Tasks 183Formatting Cell Ranges 183Comparing Macros in Excel and Access 183Creating Macros in Microsoft Excel 184Creating Macros in Microsoft Access 184
Introducing Excel Macros 184
Using the Macro Recorder 185The Macro Recorder User Interface 185Recording Macros with Absolute References 188Recording Macros with Relative References 190Macro Security in Excel 2007 193Default Excel Security Settings 193The Office Trust Center 194Macro-Disabled Excel File Extensions 196Excel Macro Examples 197Macro for Navigating a Spreadsheet 197Macro for Formatting 203
Macros in Microsoft Access 206
Macro Security in Access 2007 207Creating your First Access Macro 209The Macro Design Template 210Common Actions in Access Macros 211Access Macro Example 217
xii Contents
02_104880 ftoc.qxp 3/22/07 10:47 PM Page xii
Trang 16Part II: Advanced Integration Techniques 225
What Is VBA? 228
VBA as an Object-Oriented Programming Language 229Objects and Collections 229Properties, Methods, and Arguments 230Extended Analogy of the Object Model 231
The Visual Basic Editor or VBE 232
Project Explorer Window 234
Code and Events 234
Object Variables 236Array Variables 237
Declaring Variables 237Variable Scope 238
Procedures and Functions 238
VBA Coding Fundamentals 243
Code that Manipulates Objects 244With End With Construct 244For Each-Next Construct 245Code that Controls Execution 245For Next Construct 245
Do Until Loop Construct 246Looping Code: Do While Loop Construct 247Logical Code: If Then and If Then Else End If
Logical Code: Select Case Construct 249
Getting Help with VBA 250
Chapter 8: Using VBA to Move Data Between Excel and Access 255
Understanding ADO Fundamentals 256
The Connection String 256Declaring a Recordset 258Return Read Only Data from a Table or Query 259Return Updateable Data from a Table or Query 260Writing Your First ADO Procedure 260Referencing the ADO Object Library 260Writing the Code 262Using the Code 264
Contents xiii
Trang 17Understanding SQL Fundamentals 265
Basic SQL Syntax to Select Data 265The SELECT Statement 265Selecting All Columns 266The WHERE Clause 266Expanding Your Search with the Like Operator 267Grouping and Aggregating with the GROUP BY Clause 268The HAVING Clause 268Creating Aliases with the AS Clause 269Setting Sort Order with the ORDER BY Clause 269SELECT TOP and SELECT TOP PERCENT 270Writing Your First ADO/SQL Data Extract 270Using Criteria in Your SQL Statements 272Set Numeric Criteria 272Set Textual Criteria 272Set Date Criteria 273Set Multiple Criteria 273Using the LIKE Operator 273
Common Scenarios Where VBA Can Help 275
Query Data from an Excel Workbook 275Append Records to an Existing Excel Table 278Append Excel Records to an Existing Access Table 280Querying Text Files 282
Chapter 9: Exploring Excel and Access Automation 285
Understanding the Concept of Binding 285
Early Binding 286
Automating Excel from Access 287
Creating Your First Excel Automation Procedure 287Automating Data Export to Excel 290Sending One Recordset to Excel 290Sending Two Datasets to Two Different Tabs
in the Same Workbook 292Automating Excel Reports: Without Programming Excel 293Using Find and Replace to Adjust Macro-Generated Code 300Running an Excel Macro from Access 301Optimizing Macro-Generated Code 303Removing Navigation Actions 303Deleting Code That Specifies Default Settings 304Cleaning Up Double Takes and Mistakes 305Temporarily Disabling Screen Updating 306
Automating Access from Excel 306
Setting the Required References 307Running an Access Query from Excel 307
xiv Contents
02_104880 ftoc.qxp 3/22/07 10:47 PM Page xiv
Trang 18Running Access Parameter Queries from Excel 309Running an Access Macro from Excel 314Opening an Access Report from Excel 315Opening an Access Form from Excel 315Compacting an Access Database from Excel 316
Creating a Simple Reporting Solution with XML 327
Exporting XML Data from Access 327Utilizing XML Data in Excel 330
Creating a Data Entry Process Using XML 332
Creating the Data Entry Schema in Access 332Setting Up the Data Entry Form in Excel 334Exporting Results from Excel to XML 335Getting the Results Back into Access 336
Chapter 11: Integrating Excel and Other Office Applications 339
Integrating Excel with Microsoft Word 339
Creating a Dynamic Link to an Excel Table 340Getting Excel Data to a Word Document Using Automation 344Creating a Word Mail Merge Document 346Simulating the Word Mail Merge Function from Excel 351
Integrating Excel with PowerPoint 354
Creating a PowerPoint Slide with a Title 355Copying a Range of Cells to a Presentation 357Sending All Excel Charts to the Presentation 359Converting a Workbook into a PowerPoint Presentation 361
Integrating Excel and Outlook 364
Mailing the Active Workbook 364Mailing a Specific Range 366Mailing to All E-mail Addresses in Your Contact List 367Saving All Attachments in a Folder 369Saving Certain Attachments to a Folder 371
Contents xv
Trang 19We would like to express our deepest thanks to Katie Mohr and Kelly Talbot,for all the hours of work put into making this book as clear as it can be Thanksalso to Ed Ferraro for saving us from embarrassment as he worked to correctour mistakes and suggest numerous improvements in our examples and text.Any errors you may find here are ours, not his We would also like to thank thebrilliant team of professionals who helped bring this book to fruition Finally,
a special thank you goes out to our families for putting up with all the time wespent away on this project
Acknowledgments
xvi
03_104880 flast.qxp 3/22/07 10:48 PM Page xvi
Trang 20Since Office 2000, Microsoft has marketed the Office suite as a set of able applications that easily enable integration of multiple processes For mostusers, however, Office is still a suite of individual applications Excel is usedfor spreadsheet analysis and reporting whereas Access is used for databasefunctions—and that’s it Indeed, most mainstream training courses and docu-mentation are often dedicated to one application or another, often providingvery little information on the concept of integration.
interoper-In fact, it seems that most Office users tend to fall in one of two camps: Excelusers and Access users Very few people operate comfortably in both camps.Even fewer realize the full integration potential of these powerful Office appli-cations
Microsoft Excel reigns supreme among spreadsheet applications In the porate world, Excel is a ubiquitous and nearly universal application This pop-ularity has come with a severe downside as most business analysts haveconstrained themselves to just one tool for all their analytical and reportingneeds — Excel What’s the problem with that? Well, Excel is not designed to
cor-do many of the activities we try to make it cor-do — like integrating disparate datasources and performing complex, multi-stage data processing Rather thanexplore the functionality of other Office applications (namely Access), analystsinstead engage in hand-to-hand combat with their data, creating complexworkarounds and inefficient processes
As a relational database application, Microsoft Access enables integration ofdisparate data sources and multi-step data manipulation that would be cum-bersome or even impossible to do in Excel However, Access has its limitations
in the business community First, it does not have a fraction of the popularitythat Excel has Chances are that nearly everyone in your company, from the
Introduction
xvii