Tải bản đầy đủ (.pdf) (1,567 trang)

wiley excel 2013 power programming with vba

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 (29.37 MB, 1,567 trang )

Excel
®
2013 Power Programming
with VBA
Table of Contents
Introduction
Topics Covered
What You Need to Know
What You Need to Have
Conventions in This Book
Excel commands
Visual Basic Editor commands
Keyboard conventions
Mouse conventions
What the Icons Mean
How This Book Is Organized
Part I: Some Essential Background
Part II: Understanding Visual Basic for Applications
Part III: Working with UserForms
Part IV: Advanced Programming Techniques
Part V: Developing Applications
Part VI: Other Topics
Part VII: Appendixes
About This Book's Website
About the Power Utility Pak Offer
How to Use This Book
Part I: Some Essential Background
Chapter 1: Excel in a Nutshell
About Excel
Thinking in Terms of Objects


Workbooks
Worksheets
Chart sheets
XLM macro sheets
Excel 5 and 95 dialog sheets
Excel's User Interface
About the Ribbon
Shortcut menus and the Mini toolbar
Dialog boxes
Task pane
Keyboard shortcuts
Data Entry
Formulas, Functions, and Names
Selecting Objects
Formatting
Protection Options
Protecting formulas from being overwritten
Protecting a workbook's structure
Applying password protection to a workbook
Protecting VBA code with a password
Charts
Shapes and SmartArt
Database Access
Worksheet databases
External databases
Internet Features
Analysis Tools
Add-Ins
Macros and Programming
File Format

Excel's Help System
Chapter 2: Formula Tricks and Techniques
About Formulas
Calculating Formulas
Cell and Range References
Why use references that aren't relative?
About R1C1 notation
Referencing other sheets or workbooks
Using Names
Naming cells and ranges
Applying names to existing references
Intersecting names
Naming columns and rows
Scoping names
Naming constants
Naming formulas
Naming objects
Formula Errors
Excel Auditing Tools
Identifying cells of a particular type
Viewing formulas
Tracing cell relationships
Tracing error values
Fixing circular reference errors
Using the background error-checking feature
Using Excel's Formula Evaluator
Array Formulas
An array formula example
An array formula calendar
Array formula pros and cons

Counting and Summing Techniques
Counting formula examples
Summing formula examples
Other counting tools
Lookup Formulas
Working with Dates and Times
Entering dates and times
Using pre-1900 dates
Creating Megaformulas
Chapter 3: Understanding Excel Files
Starting Excel
File Types
Excel file formats
Text file formats
Database file formats
Other file formats
Excel File Compatibility
Protected View
Using AutoRecover
Recovering versions of the current workbook
Recovering unsaved work
Configuring AutoRecover
Working with Template Files
Viewing templates
Creating templates
Creating workbook templates
Inside an Excel File
Dissecting a file
Why is the file format important?
The OfficeUI File

The XLB File
Add-In Files
Excel Settings in the Registry
About the Registry
Excel's settings
Chapter 4: Essentials of Spreadsheet Application Development
What Is a Spreadsheet Application?
Steps for Application Development
Determining User Needs
Planning an Application That Meets User Needs
Determining the Most Appropriate User Interface
Customizing the Ribbon
Customizing shortcut menus
Creating shortcut keys
Creating custom dialog boxes
Using ActiveX controls on a worksheet
Executing the development effort
Concerning Yourself with the End User
Testing the application
Making the application bulletproof
Making the application aesthetically appealing and intuitive
Creating a user Help system
Documenting the development effort
Distributing the application to the user
Updating the application when necessary
Other Development Issues
The user's installed version of Excel
Language issues
System speed
Video modes

Part II: Understanding Visual Basic for Applications
Chapter 5: Introducing Visual Basic for Applications
Getting Some BASIC Background
Delving into VBA
Object models
VBA versus XLM
Covering the Basics of VBA
Introducing Visual Basic Editor
Displaying Excel's Developer tab
Activating VBE
VBE windows
Working with Project Explorer
Adding a new VBA module
Removing a VBA module
Exporting and importing objects
Working with Code Windows
Minimizing and maximizing windows
Storing VBA code
Entering VBA code
Customizing the VBE Environment
Using the Editor tab
Using the Editor Format tab
Using the General tab
Using the Docking tab
The Macro Recorder
What the macro recorder actually records
Relative or absolute recording?
Recording options
Cleaning up recorded macros
About Objects and Collections

The object hierarchy
About collections
Referring to objects
Properties and Methods
Object properties
Object methods
The Comment Object: A Case Study
Viewing Help for the Comment object
Properties of a Comment object
Methods of a Comment object
The Comments collection
About the Comment property
Objects contained in a Comment object
Determining whether a cell has a comment
Adding a new Comment object
Some Useful Application Properties
Working with Range Objects
The Range property
The Cells property
The Offset property
Things to Know about Objects
Essential concepts to remember
Learning more about objects and properties
Chapter 6: VBA Programming Fundamentals
VBA Language Elements: An Overview
Comments
Variables, Data Types, and Constants
Defining data types
Declaring variables
Scoping variables

Working with constants
Working with strings
Working with dates
Assignment Statements
Arrays
Declaring arrays
Declaring multidimensional arrays
Declaring dynamic arrays
Object Variables
User-Defined Data Types
Built-in Functions
Manipulating Objects and Collections
With-End With constructs
For Each-Next constructs
Controlling Code Execution
GoTo statements
If-Then constructs
Select Case constructs
Looping blocks of instructions
Chapter 7: Working with VBA Sub Procedures
About Procedures
Declaring a Sub procedure
Scoping a procedure
Executing Sub Procedures
Executing a procedure with the Run Sub/UserForm command
Executing a procedure from the Macro dialog box
Executing a procedure with a Ctrl+shortcut key combination
Executing a procedure from the Ribbon
Executing a procedure from a customized shortcut menu
Executing a procedure from another procedure

Executing a procedure by clicking an object
Executing a procedure when an event occurs
Executing a procedure from the Immediate window
Passing Arguments to Procedures
Error-Handling Techniques
Trapping errors
Error-handling examples
A Realistic Example That Uses Sub Procedures
The goal
Project requirements
What you know
The approach
What you need to know
Some preliminary recording
Initial setup
Code writing
Writing the Sort procedure
More testing
Fixing the problems
Utility availability
Evaluating the project
Chapter 8: Creating Function Procedures
Sub Procedures versus Function Procedures
Why Create Custom Functions?
An Introductory Function Example
Using the function in a worksheet
Using the function in a VBA procedure
Analyzing the custom function
Function Procedures
A function's scope

Executing function procedures
Function Arguments
Function Examples
Functions with no argument
A function with one argument
A function with two arguments
A function with an array argument
A function with optional arguments
A function that returns a VBA array
A function that returns an error value
A function with an indefinite number of arguments
Emulating Excel's SUM function
Extended Date Functions
Debugging Functions
Dealing with the Insert Function Dialog Box
Using the MacroOptions method
Specifying a function category
Adding a function description manually
Using Add-ins to Store Custom Functions
Using the Windows API
Windows API examples
Determining the Windows directory
Detecting the Shift key
Learning more about API functions
Chapter 9: VBA Programming Examples and Techniques
Learning by Example
Working with Ranges
Copying a range
Moving a range
Copying a variably sized range

Selecting or otherwise identifying various types of ranges
Resizing a range
Prompting for a cell value
Entering a value in the next empty cell
Pausing a macro to get a user-selected range
Counting selected cells
Determining the type of selected range
Looping through a selected range efficiently
Deleting all empty rows
Duplicating rows a variable number of times
Determining whether a range is contained in another range
Determining a cell's data type
Reading and writing ranges
A better way to write to a range
Transferring one-dimensional arrays
Transferring a range to a variant array
Selecting cells by value
Copying a noncontiguous range
Working with Workbooks and Sheets
Saving all workbooks
Saving and closing all workbooks
Hiding all but the selection
Creating a hyperlink table of contents
Synchronizing worksheets
VBA Techniques
Toggling a Boolean property
Displaying the date and time
Displaying friendly time
Getting a list of fonts
Sorting an array

Processing a series of files
Some Useful Functions for Use in Your Code
The FileExists function
The FileNameOnly function
The PathExists function
The RangeNameExists function
The SheetExists function
The WorkbookIsOpen function
Retrieving a value from a closed workbook
Some Useful Worksheet Functions
Returning cell formatting information
A talking worksheet
Displaying the date when a file was saved or printed
Understanding object parents
Counting cells between two values
Determining the last nonempty cell in a column or row
Does a string match a pattern?
Extracting the nth element from a string
Spelling out a number
A multifunctional function
The SHEETOFFSET function
Returning the maximum value across all worksheets
Returning an array of nonduplicated random integers
Randomizing a range
Sorting a range
Windows API Calls
Determining file associations
Determining disk drive information
Determining default printer information
Determining video display information

Reading from and writing to the Registry
Part III: Working with UserForms
Chapter 10: Custom Dialog Box Alternatives
Before You Create That UserForm . . .
Using an Input Box
The VBA InputBox function
The Excel InputBox method
The VBA MsgBox Function
The Excel GetOpenFilename Method
The Excel GetSaveAsFilename Method
Prompting for a Directory
Displaying Excel's Built-In Dialog Boxes
Displaying a Data Form
Making the data form accessible
Displaying a data form by using VBA
Chapter 11: Introducing UserForms
How Excel Handles Custom Dialog Boxes
Inserting a New UserForm
Adding Controls to a UserForm
Toolbox Controls
CheckBox
ComboBox
CommandButton
Frame
Image
Label
ListBox
MultiPage
OptionButton
RefEdit

ScrollBar
SpinButton
TabStrip
TextBox
ToggleButton
Adjusting UserForm Controls
Adjusting a Control's Properties
Using the Properties window
Common properties
Accommodating keyboard users
Displaying a UserForm
Adjusting the display position
Displaying a modeless UserForm
Displaying a UserForm based on a variable
Loading a UserForm
About event-handler procedures
Closing a UserForm
Creating a UserForm: An Example
Creating the UserForm
Writing code to display the dialog box
Testing the dialog box
Adding event-handler procedures
Validating the data
The finished dialog box
Understanding UserForm Events
Learning about events
UserForm events
SpinButton events
Pairing a SpinButton with a TextBox
Referencing UserForm Controls

Customizing the Toolbox
Adding new pages to the Toolbox
Customizing or combining controls
Adding new ActiveX controls
Creating UserForm Templates
A UserForm Checklist
Chapter 12: UserForm Examples
Creating a UserForm “Menu”
Using CommandButtons in a UserForm
Using a ListBox in a UserForm
Selecting Ranges from a UserForm
Creating a Splash Screen
Disabling a UserForm's Close Button
Changing a UserForm's Size
Zooming and Scrolling a Sheet from a UserForm
ListBox Techniques
Adding items to a ListBox control
Determining the selected item in a ListBox
Determining multiple selections in a ListBox
Multiple lists in a single ListBox
ListBox item transfer
Moving items in a ListBox
Working with multicolumn ListBox controls
Using a ListBox to select worksheet rows
Using a ListBox to activate a sheet
Using the MultiPage Control in a UserForm
Using an External Control
Animating a Label
Chapter 13: Advanced UserForm Techniques
A Modeless Dialog Box

Displaying a Progress Indicator
Creating a stand-alone progress indicator
Showing a progress indicator by using a MultiPage control
Showing a progress indicator without using a MultiPage control
Creating Wizards
Setting up the MultiPage control for the wizard
Adding the buttons to the wizard's UserForm
Programming the wizard's buttons
Programming dependencies in a wizard
Performing the task with the wizard
Emulating the MsgBox Function
MsgBox emulation: MyMsgBox code
How the MyMsgBox function works
Using the MyMsgBox function
A UserForm with Movable Controls
A UserForm with No Title Bar
Simulating a Toolbar with a UserForm
Emulating a Task Pane with a UserForm
A Resizable UserForm
Handling Multiple UserForm Controls with One Event Handler
Selecting a Color in a UserForm
Displaying a Chart in a UserForm
Saving a chart as a GIF file
Changing the Image control's Picture property
Making a UserForm Semitransparent
An Enhanced Data Form
About the Enhanced Data Form
Installing the Enhanced Data Form add-in
A Puzzle on a UserForm
Video Poker on a UserForm

Part IV: Advanced Programming Techniques
Chapter 14: Developing Excel Utilities with VBA
About Excel Utilities
Using VBA to Develop Utilities
What Makes a Good Utility?
Text Tools: The Anatomy of a Utility
Background for Text Tools
Project goals for Text Tools
The Text Tools workbook
How the Text Tools utility works
The UserForm for the Text Tools utility
The Module1 VBA module
The UserForm1 code module
Making the Text Tools utility efficient
Saving the Text Tools utility settings
Implementing Undo
Displaying the Help file
Adding the RibbonX code
Post-mortem of the project
Understand the Text Tools utility
More about Excel Utilities
Chapter 15: Working with Pivot Tables
An Introductory Pivot Table Example
Creating a pivot table
Examining the recorded code for the pivot table
Cleaning up the recorded pivot table code
Creating a More Complex Pivot Table
The code that created the pivot table
How the more complex pivot table works
Creating Multiple Pivot Tables

Creating a Reverse Pivot Table
Chapter 16: Working with Charts
Getting the Inside Scoop on Charts
Chart locations
The macro recorder and charts
The Chart object model
Creating an Embedded Chart
Creating a Chart on a Chart Sheet
Modifying Charts
Using VBA to Activate a Chart
Moving a Chart
Using VBA to Deactivate a Chart
Determining Whether a Chart Is Activated
Deleting from the ChartObjects or Charts Collection
Looping through All Charts
Sizing and Aligning ChartObjects
Creating Lots of Charts
Exporting a Chart
Exporting all graphics
Changing the Data Used in a Chart
Changing chart data based on the active cell
Using VBA to determine the ranges used in a chart
Using VBA to Display Arbitrary Data Labels on a Chart
Displaying a Chart in a UserForm
Understanding Chart Events
An example of using Chart events
Enabling events for an embedded chart
Example: Using Chart events with an embedded chart
Discovering VBA Charting Tricks
Printing embedded charts on a full page

Hiding series by hiding columns
Creating unlinked charts
Displaying text with the MouseOver event
Animating Charts
Scrolling a chart
Creating a hypocycloid chart
Creating a clock chart
Creating an Interactive Chart without VBA
Getting the data to create an interactive chart
Creating the Option Button controls for an interactive chart
Creating the city lists for the interactive chart
Creating the interactive chart data range
Creating the interactive chart
Working with Sparkline Charts
Chapter 17: Understanding Excel's Events
What You Should Know about Events
Understanding event sequences
Where to put event-handler procedures
Disabling events

×