Excel 2019 Power Programming with VBA
By Dick Kusleika and Michael Alexander
5/5
()
About this ebook
Excel 2019 Power Programming with VBA is fully updated to cover all the latest tools and tricks of Excel 2019. Encompassing an analysis of Excel application development and a complete introduction to Visual Basic for Applications (VBA), this comprehensive book presents all of the techniques you need to develop both large and small Excel applications. Over 800 pages of tips, tricks, and best practices shed light on key topics, such as the Excel interface, file formats, enhanced interactivity with other Office applications, and improved collaboration features.
Understanding how to leverage VBA to improve your Excel programming skills can enhance the quality of deliverables that you produce—and can help you take your career to the next level.
- Explore fully updated content that offers comprehensive coverage through over 900 pages of tips, tricks, and techniques
- Leverage templates and worksheets that put your new knowledge in action, and reinforce the skills introduced in the text
- Improve your capabilities regarding Excel programming with VBA, unlocking more of your potential in the office
Excel 2019 Power Programming with VBA is a fundamental resource for intermediate to advanced users who want to polish their skills regarding spreadsheet applications using VBA.
Read more from Dick Kusleika
Data Visualization with Excel Dashboards and Reports Rating: 4 out of 5 stars4/5Excel Macros For Dummies Rating: 0 out of 5 stars0 ratingsMicrosoft 365 Excel VBA Programming For Dummies Rating: 0 out of 5 stars0 ratingsExcel Quick and Easy Rating: 0 out of 5 stars0 ratings
Related to Excel 2019 Power Programming with VBA
Related ebooks
Excel VBA Recipes Rating: 4 out of 5 stars4/5Excel VBA: A Beginners' Guide Rating: 4 out of 5 stars4/5Mastering VBA for Microsoft Office 365 Rating: 5 out of 5 stars5/5Excel Dashboards and Reports for Dummies Rating: 4 out of 5 stars4/5Excel VBA: A Step-By-Step Tutorial For Beginners To Learn Excel VBA Programming From Scratch: 1 Rating: 4 out of 5 stars4/5The Ultimate Excel VBA Master: A Complete, Step-by-Step Guide to Becoming Excel VBA Master from Scratch Rating: 0 out of 5 stars0 ratingsMastering Excel Macros: Introduction: Mastering Excel Macros, #1 Rating: 4 out of 5 stars4/5Secrets of MS Excel VBA Macros for Beginners !: Save Your Time With Visual Basic Macros! Rating: 4 out of 5 stars4/5Learn Excel in 24 Hours Rating: 4 out of 5 stars4/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Excel : The Complete Ultimate Comprehensive Step-By-Step Guide To Learn Excel Programming Rating: 0 out of 5 stars0 ratingsExcel Macros For Dummies Rating: 3 out of 5 stars3/5101 Ready-to-Use Excel Formulas Rating: 4 out of 5 stars4/5Mastering Microsoft Excel 2016: How to Master Microsoft Excel 2016 in 30 days Rating: 5 out of 5 stars5/5Learn Excel from Mr. Excel: 277 Excel Mysteries Solved Rating: 4 out of 5 stars4/5Excel 2016 For Dummies Rating: 4 out of 5 stars4/5Excel Macros - A Step-by-Step Illustrated Guide to Learn Excel Macros Rating: 0 out of 5 stars0 ratingsMicrosoft Excel: Advanced Microsoft Excel Data Analysis for Business Rating: 0 out of 5 stars0 ratingsExcel Guide for Success Rating: 5 out of 5 stars5/5Excel :The Ultimate Comprehensive Step-by-Step Guide to Strategies in Excel Programming (Formulas, Shortcuts and Spreadsheets): 2 Rating: 0 out of 5 stars0 ratingsEXCEL: Microsoft: Boost Your Productivity Quickly! Learn Excel, Spreadsheets, Formulas, Shortcuts, & Macros Rating: 0 out of 5 stars0 ratingsExcel 2021 Rating: 4 out of 5 stars4/5The Ultimate Guide To Microsoft Excel Vba For Beginners And Seniors Rating: 0 out of 5 stars0 ratings101 Most Popular Excel Formulas: 101 Excel Series, #1 Rating: 4 out of 5 stars4/5Excel 2019 For Dummies Rating: 3 out of 5 stars3/5150 Most Poweful Excel Shortcuts: Secrets of Saving Time with MS Excel Rating: 3 out of 5 stars3/5
Enterprise Applications For You
Creating Online Courses with ChatGPT | A Step-by-Step Guide with Prompt Templates Rating: 4 out of 5 stars4/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Notion for Beginners: Notion for Work, Play, and Productivity Rating: 4 out of 5 stars4/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsQuickBooks 2023 All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsMicrosoft Teams For Dummies Rating: 0 out of 5 stars0 ratingsExcel Formulas and Functions 2020: Excel Academy, #1 Rating: 4 out of 5 stars4/5Learning Microsoft Endpoint Manager: Unified Endpoint Management with Intune and the Enterprise Mobility + Security Suite Rating: 0 out of 5 stars0 ratingsBitcoin For Dummies Rating: 4 out of 5 stars4/5Some Future Day: How AI Is Going to Change Everything Rating: 0 out of 5 stars0 ratingsQuickBooks 2024 All-in-One For Dummies Rating: 0 out of 5 stars0 ratings50 Useful Excel Functions: Excel Essentials, #3 Rating: 5 out of 5 stars5/5Agile Project Management: Scrum for Beginners Rating: 4 out of 5 stars4/5Microsoft Excel 365 Bible Rating: 0 out of 5 stars0 ratingsMicrosoft Excel Formulas: Master Microsoft Excel 2016 Formulas in 30 days Rating: 4 out of 5 stars4/5Excel All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsExcel 2019 Bible Rating: 5 out of 5 stars5/5CompTIA Project+ Study Guide: Exam PK0-005 Rating: 0 out of 5 stars0 ratingsEssential Office 365 Third Edition: The Illustrated Guide to Using Microsoft Office Rating: 3 out of 5 stars3/5Teach Yourself VISUALLY Microsoft 365 Rating: 0 out of 5 stars0 ratingsExcel 2019 For Dummies Rating: 3 out of 5 stars3/5Scrivener For Dummies Rating: 4 out of 5 stars4/5
Reviews for Excel 2019 Power Programming with VBA
1 rating0 reviews
Book preview
Excel 2019 Power Programming with VBA - Dick Kusleika
Introduction
For most of us, the path to Excel VBA programming starts with the need to perform some task that can't be done with the standard tools in Excel. That task is different for each of us. Maybe that task is to create separate workbooks automatically for all the rows in a data set. Maybe that task is to automate the emailing of dozens of reports. Whatever that task is for you, you can bet that someone has started their own journey into Excel VBA with the same need.
The beautiful thing about Excel VBA is that you don't have to be an expert to start solving problems with it. You can learn just enough to solve a particular problem, or you can go further and discover ways to handle all kinds of automation scenarios.
Whatever your goals may be, Excel 2019 Power Programming with VBA will help you harness the power of the VBA language to automate tasks, work smarter, and be more productive.
Topics Covered
This book focuses on Visual Basic for Applications (VBA), the programming language built into Excel (and other applications that make up Microsoft Office). More specifically, it shows you how to write programs that automate various tasks in Excel. This book covers everything from recording simple macros through creating sophisticated user-oriented applications and utilities.
You can approach this book in any way you please. You can read it from cover to cover, or you can skip around, picking up useful tidbits here and there. VBA programming is often a task-oriented endeavor. So, if you're faced with a challenging task, you might try the index first to see where the book might specifically address your problem.
This book does not cover Microsoft Visual Studio Tools for Office (VSTO), a technology that uses Visual Basic .NET and Microsoft Visual C#. VSTO can also be used to control Excel and other Microsoft Office applications.
As you may know, Excel 2019 is available for other platforms. For example, you can use Microsoft's Excel Web App in your browser and even iPads and tablets. These versions do not support VBA. In other words, this book is for the desktop version of Excel 2019 for Windows.
What You Need to Know
This is not a book for beginning Excel users. If you have no experience with Excel, a better choice might be the Excel 2019 Bible (Wiley, 2018), which provides comprehensive coverage of all the features of Excel and is meant for users of all levels.
To get the most out of this book, you should be a relatively experienced Excel user who knows how to do the following:
Create workbooks, insert sheets, save files, and so on
Navigate through a workbook
Use the Excel Ribbon user interface
Enter formulas
Use Excel's worksheet functions
Name cells and ranges
Use basic Windows features, such as file management techniques and the Clipboard
What You Need to Have
Excel is available in several versions, including a web version and a version for tablets and phones. This book was written exclusively for the desktop version of Microsoft Excel 2019 for Windows. If you plan to develop applications that will be used in earlier versions of Excel, we strongly suggest you use the earliest version of Excel that your target audience will be using. Over the last few years, Microsoft has adopted an agile release cycle for the web version of Excel with Office 365, generating release updates practically on a monthly basis.
It is important to have a full installation of Excel, and if you want to try the more advanced chapters involving communication between Excel and other Office applications, you will need a full installation of Office.
The version of Windows you use is not important. Any computer system that can run Windows will suffice, but you'll be much better off with a fast machine with plenty of memory. Excel is a large program, and using it on a slower system or a system with minimal memory can be extremely frustrating.
Please note that this book is not applicable to Microsoft Excel for Mac.
Conventions Used in This Book
Take a minute to skim this section and learn about some of the typographic conventions used throughout this book.
Excel commands
Excel uses a context-sensitive Ribbon menu system. The words along the top (such as Insert and View) are known as tabs. Click a tab, and the Ribbon of icons displays the commands that are most suited to the task at hand. Each icon has a name that is (usually) displayed next to or below the icon. The icons are arranged in groups, and the group name appears below the icons.
The convention used in this book is to indicate the tab name, followed by the group name, followed by the icon name. So, for example, the command used to toggle word wrap in a cell is indicated as follows:
Home ➪ Alignment ➪ Wrap Text
Clicking the first tab, labeled File, takes you to the Backstage window. The Backstage window has commands along the left side of the window. To indicate Backstage commands, we use the word File, followed by the command. For example, the following command displays the Excel Options dialog box:
File ➪ Options
Visual Basic Editor commands
Visual Basic Editor is the window in which you will work with your VBA code. VB Editor uses the traditional menu-and-toolbar interface. A command like the following means to click the Tools menu and select the References menu item:
Tools ➪ References
Keyboard conventions
You need to use the keyboard to enter data. In addition, you can work with menus and dialog boxes directly from the keyboard—a method that you might find easier if your hands are already positioned over the keys.
Input
Inputs that you are supposed to type from the keyboard will appear in boldface—for example, enter =SUM(B2: B50) in cell B51.
Lengthier inputs will appear on a separate line in a monospace font. For example, we might instruct you to enter the following formula:
=VLOOKUP(StockNumber,PriceList,2)
VBA code
This book contains many snippets of VBA code, as well as complete procedure listings. Each listing appears in a monospace font, and each line of code occupies a separate line. (We copied these listings directly from the VBA module and pasted them into our word processors.) To make the code easier to read, we often use one or more tabs to create indentations. Indentation is optional, but it does help to delineate statements that go together.
If a line of code doesn't fit on a single line in this book, we use the standard VBA line continuation sequence: at the end of a line, a space followed by an underscore character indicates that the line of code extends to the next line. For example, the following two lines are a single code statement:
columnCount = Application.WorksheetFunction. _ CountA(Range(A:A
)) + 1
You can enter this code either on two lines, exactly as shown, or on a single line without the space and underscore character.
Functions, filenames, and named ranges
Excel's worksheet functions appear in uppercase font, like so: Enter a SUM formula in cell C20.
For VBA procedure names, properties, methods, and objects, we often use mixed uppercase and lowercase letters to make these names easier to read.
Typographical conventions
Anything that you're supposed to type using the keyboard appears in bold. Lengthy input usually appears on a separate line. Here's an example:
=Part Name:
&VLOOKUP(PartNumber,PartList,2)
Names of the keys on your keyboard appear in normal type. When two keys should be pressed simultaneously, they're connected with a plus sign, like this: Press Ctrl+C to copy the selected cells.
The four arrow
keys are collectively known as the navigation keys.
Excel built-in worksheet functions appear in monofont in uppercase like this: Note the SUMPRODUCT function used in cell C20.
Mouse conventions
You'll come across some of the following mouse-related terms, which are all standard fare.
Mouse pointer This is the small graphic figure that moves on-screen when you move your mouse. The mouse pointer is usually an arrow, but it changes shape when you move to certain areas of the screen or when you're performing certain actions.
Point Move the mouse so that the mouse pointer is on a specific item; for example, Point to the Save button on the toolbar.
Click Press the left mouse button once and release it immediately.
Right-click Press the right mouse button once and release it immediately. The right mouse button is used in Excel to open shortcut menus that are appropriate for whatever is currently selected.
Double-click Press the left mouse button twice in rapid succession.
Drag Press the left mouse button and keep it pressed while you move the mouse. Dragging is often used to select a range of cells or to change the size of an object.
What the Icons Mean
Throughout the book, we use icons to call your attention to points that are particularly important.
NOTE
We use Note icons to tell you that something is important—perhaps a concept that could help you master the task at hand or something fundamental for understanding subsequent material.
TIP
Tip icons indicate a more efficient way of doing something or a technique that might not be obvious.
Arrow_icon These icons are used to refer to other section or chapters that have more to say on a subject.
CAUTION
We use caution icons when the operation that we're describing can cause problems if you're not careful.
ON THE WEB
These icons indicate that an example file is available on the book’s website. See the section What’s on the Website
later in this introduction.
How This Book Is Organized
The chapters of this book are grouped into five main parts.
Part I: Introduction to Excel VBA
In Part I, we introduce you to VBA, providing the programming fundamentals that you will need to create and manage Excel subroutines and functions. Chapter 1 sets the stage with a conceptual overview of Excel application development. Chapters 2 through 6 cover everything you need to know to start coding in VBA. Chapter 7 rounds out your introduction to VBA with many useful examples.
Part II: Advanced VBA Techniques
Part II covers additional techniques that are often considered advanced. Chapters 8 and 9 discuss how to use VBA to work with pivot tables and charts (including Sparkline graphics). Chapter 10 discusses various techniques that you can use to interact with other applications (such as Word and Outlook). Chapter 11 concludes Part II with a discussion on how to work with files and external data sources, including how to control Power Query from VBA.
Part III: Working with UserForms
The four chapters in Part III cover custom dialog boxes (UserForms). Chapter 12 presents some built-in alternatives to creating custom UserForms. Chapter 13 provides an introduction to UserForms and the various controls that you can use. Chapters 14 and 15 present many examples of custom dialog boxes, ranging from basic to advanced.
Part IV: Developing Excel Applications
The chapters in Part IV deal with important elements of creating user-oriented applications. Chapter 16 offers a hands-on discussion of creating add-ins. Chapters 17 and 18 discuss how to modify Excel's Ribbon and shortcut menus. Chapter 19 demonstrates several ways to provide online help for your applications. In Chapter 20, we present a primer on developing user-oriented applications. Chapter 21 rounds out your exploration of Excel VBA programming with some information regarding compatibility.
Part V: Appendix
Part V includes an appendix that offers a reference guide to all the statements and functions exposed to VBA as keywords.
How to Use This Book
The topics in this book get more advanced as you progress through it, so you can work through the material from front to back and build your skills as you go. You can also use this book as a reference that you can consult when you need help with the following situations:
You're stuck while trying to do something
You need to do something that you've never done before
You have some time on your hands, and you're interested in learning something new about VBA
The index is comprehensive, and each chapter typically focuses on a single broad topic. Don't be discouraged if some of the material is over your head. Most VBA programmers get by just fine by using only a subset of the language.
What's on the Website
Nearly everything discussed in this book has examples with it. You can (and should) download the many useful examples included with this book.
The files are located at www.wiley.com/go/excel2019powerprogramming.
Part I
Introduction to Excel VBA
IN THIS PART
Chapter 1 Essentials of Spreadsheet Application Development
Chapter 2 Introducing Visual Basic for Applications
Chapter 3 VBA Programming Fundamentals
Chapter 4 Working with VBA Sub Procedures
Chapter 5 Creating Function Procedures
Chapter 6 Understanding Excel's Events
Chapter 7 VBA Programming Examples and Techniques
CHAPTER 1
Essentials of Spreadsheet Application Development
IN THIS CHAPTER
Discovering the basic steps involved in spreadsheet application development
Determining end users' needs
Planning applications to meet users' needs
Developing and testing your applications
Documenting your development efforts and writing user documentation
What Is a Spreadsheet Application?
For the purposes of this book, a spreadsheet application is a spreadsheet file (or group of related files) that is designed so that someone other than the developer can perform specific tasks without extensive training. According to this definition, most of the spreadsheet files that you've developed probably don't qualify as spreadsheet applications. You may have dozens or hundreds of spreadsheet files on your hard drive, but it's a safe bet that most of them aren't designed for others to use.
A good spreadsheet application does the following:
Enables the end user to perform a task that he or she probably would not be able to do otherwise.
Provides the appropriate solution to the problem. (A spreadsheet environment isn't always the optimal approach.)
Accomplishes what it is supposed to do. This prerequisite may be obvious, but it's not at all uncommon for applications to fail this test.
Produces accurate results and is free of bugs.
Uses appropriate and efficient methods and algorithms to accomplish its job.
Traps errors before the user is forced to deal with them.
Does not allow the user to delete or modify important components accidentally (or intentionally).
Has a clear and consistent user interface so that the user always knows how to proceed.
Has well-documented formulas, macros, and user interface elements that allow for subsequent changes, if necessary.
Is designed so that it can be modified in simple ways without making major changes. A basic fact is that a user's needs change over time.
Has an easily accessible help system that provides useful information on at least the major procedures.
Is designed to be portable and to run on any system that has the proper software (in this case, a copy of a supported version of Excel).
It should come as no surprise that it is possible to create spreadsheet applications for many different usage levels, ranging from a simple fill-in-the-blank template to an extremely complex application that uses a custom interface and may not even look like a spreadsheet.
Steps for Application Development
There is no simple, surefire recipe for developing an effective spreadsheet application. Everyone has his or her own style for creating such applications. In addition, every project is different and therefore requires its own approach. Finally, the demands and technical expertise of the people with whom (or for whom) you work also play a role in how the development process proceeds.
Spreadsheet developers typically perform the following activities:
Determine the needs of the user(s)
Plan an application that meets these needs
Determine the most appropriate user interface
Create the spreadsheet, formulas, macros, and user interface
Test and debug the application
Attempt to make the application bulletproof
Make the application aesthetically appealing and intuitive
Document the development effort
Develop user documentation and Help systems
Distribute the application to the user
Update the application when necessary
Not all of these steps are required for each application, and the order in which these activities are performed varies from project to project. We describe each of these activities in the pages that follow. For most of these items, we cover the technical details in subsequent chapters.
Determining User Needs
When you undertake a new Excel project, one of your first steps is to identify exactly what the end users require. Failure to assess the end users' needs thoroughly early on often results in additional work later when you have to adjust the application so that it does what it was supposed to do in the first place.
In some cases, you'll be intimately familiar with the end users—you may even be an end user yourself. In other cases (for example, if you're a consultant developing a project for a new client), you may know little or nothing about the users or their situations.
How do you determine the needs of the user? If you've been asked to develop a spreadsheet application, it's a good idea to meet with the end users and ask specific questions. Better yet, get everything in writing, create flow diagrams, pay attention to minor details, and do anything else to ensure that the product you deliver is the product that is needed.
Here are some guidelines that may help make this phase easier:
Don't assume that you know what the user needs. Second-guessing at this stage almost always causes problems later.
If possible, talk directly to the end users of the application, not just their supervisor or manager.
Learn what, if anything, is currently being done to meet the users' needs. You might be able to save some work by simply adapting an existing application. At the very least, looking at current solutions will familiarize you with the operation.
Identify the resources available at the users' site. For example, try to determine whether you must work around any hardware or software limitations.
If possible, determine the specific hardware systems that will be used. If your application will be used on slow systems, you need to take that into account.
Identify which versions of Excel are in use. Keep in mind that users can have versions of Excel running on macOS, mobile platforms, and Windows. These have to be taken into account when planning an automated Excel solution. Although Microsoft does everything in its power to urge users to upgrade to the latest version of the software, the majority of Excel users don't.
Understand the skill levels of the end users. This information will help you design the application appropriately.
Determine how long the application will be used and whether any changes are anticipated during the lifetime of the project. Knowing this information may influence the amount of effort that you put into the project and help you plan for changes.
Finally, don't be surprised if the project specifications change before you complete the application. This occurrence is common, and you're in a better position if you expect changes rather than being surprised by them. Just make sure that your contract (if you have one) addresses the issue of changing specifications.
Planning an Application That Meets User Needs
After you determine the end users' needs, it's tempting to jump right in and start fiddling around in Excel. Take it from those who suffer from this problem: try to restrain yourself. Builders don't construct a house without a set of blueprints, and you shouldn't build a spreadsheet application without some type of plan. The formality of your plan depends on the scope of the project and your general style of working, but you should spend at least some time thinking about what you're going to do and coming up with a plan of action.
Before rolling up your sleeves and settling down at your keyboard, you'll benefit by taking some time to consider the various ways that you can approach the problem. This planning period is where a thorough knowledge of Excel pays off. Avoiding blind alleys rather than stumbling into them is always a good idea.
If you ask a dozen Excel experts to design an application based on precise specifications, chances are that you'll get a dozen different implementations of the project that meet those specifications. Of those solutions, some will be better than the others because Excel often provides several options to accomplish a task. If you know Excel inside and out, you'll have a good idea of the potential methods at your disposal, and you can choose the one most appropriate for the project at hand. Often, a bit of creative thinking yields an unusual approach that's vastly superior to other methods.
Consider some general options at the beginning stage of this planning period, such as the following:
File structure Think about whether you want to use one workbook with multiple sheets, several single-sheet workbooks, or a template file.
Data structure You should always consider how your data will be structured and also determine whether you will be using external database files, data sources stored on the cloud, or storing everything in worksheets.
Add-in or workbook file In some cases, an add-in may be the best choice for your final product, or perhaps you might use an add-in with a standard workbook.
Version of Excel Will your Excel application be used with Excel 2019 only, or will your application also need to run on earlier versions of Excel? What about versions of Excel running on other platforms, such as macOS or mobile devices? These considerations are important because each new version of Excel adds features that aren't available in previous versions.
Error handling Error handling is a major issue with applications. You need to determine how your application will detect and deal with errors. For example, if your application performs pivot table operations on the active sheet, you need to be able to handle a case in which a pivot table does not exist on the sheet that is active.
Use of special features If your application needs to summarize a lot of data, you may want to consider using Excel's pivot table feature, or you may want to use Excel's data validation feature as a check for valid data entry.
Performance issues The time to start thinking about increasing the speed and efficiency of your application is in the development stage, not when the application is complete and users are complaining.
Level of security As you may know, Excel provides several protection options to restrict access to particular elements of a workbook. For example, you can lock cells so that formulas cannot be changed, and you can assign a password to prevent unauthorized users from viewing or accessing specific files. Determining up front exactly what you need to protect—and what level of protection is necessary—will make your job easier.
NOTE
Be aware that Excel's protection features aren't 100 percent effective—far from it. If you desire complete and absolute security for your application, Excel probably isn't the best platform.
You'll probably have to deal with many other project-specific considerations in this phase. Consider all options, and don't settle on the first solution that comes to mind.
Another design consideration is remembering to plan for change. You'll do yourself a favor if you make your application as generic as possible. For example, don't write a procedure that works with only a specific range of cells. Rather, write a procedure that accepts any range as an argument. When the inevitable changes are requested, such a design makes it easier for you to carry out the revisions. Also, you may find that the work that you do for one project is similar to the work that you do for another. Keep reusability in mind when you are planning a project.
Avoid letting the end user completely guide your approach to a problem. For example, suppose that you meet with a manager who tells you that the department needs an application to write text files that will be imported into another application. Don't confuse the user's need with the solution. The user's real need is to share data. Using an intermediate text file to do it is just one possible solution; better ways to approach the problem may exist. In other words, don't let the users define their problem by stating it in terms of a solution approach. Determining the best approach is your job.
Determining the Most Appropriate User Interface
When you develop spreadsheets that others will use, you need to pay special attention to the user interface. By user interface, we mean the method by which the user interacts with the application and executes your VBA macros.
Since the introduction of Excel 2007, some of these user interface decisions are irrelevant. Custom menus and toolbars are, for all intents and purposes, obsolete. Consequently, developers must learn how to work with the Ribbon.
Excel provides several features that are relevant to user interface design:
Ribbon customization
Shortcut menu customization
Shortcut keys
Custom dialog boxes (UserForms)
Message boxes and input boxes
Controls (such as a ListBox or a CommandButton) placed directly on a worksheet
We discuss these features briefly in the following sections and cover them more thoroughly in later chapters.
Customizing the Ribbon
As a developer, you have a fair amount of control over the Ribbon including which tabs and commands are available when your Excel application opens. Although Excel allows end users to modify the Ribbon, making UI changes via code isn't a simple task.
Arrow_icon See Chapter 17, Working with the Ribbon,
for information about working with the Ribbon.
Customizing shortcut menus
Excel allows the VBA developer to customize the right-click shortcut menus. Right-click menus can offer users a way to trigger an action easily without having to move too far from the range in which they are working. Figure 1.1 illustrates a customized shortcut menu that appears when a cell is right-clicked.
Screenshot of a customized shortcut menu with menus such as Number Format, Alignment, Font, Fill, and Protection.FIGURE 1.1 A customized shortcut menu
Arrow_icon Chapter 18, Working with Shortcut Menus,
describes how to work with shortcut menus using VBA, including some limitations due to the single document interface introduced in Excel 2013.
Creating shortcut keys
Another user interface option at your disposal is a custom shortcut key. Excel lets you assign a Ctrl key (or Shift+Ctrl key) combination to a macro. When the user presses the key combination, the macro executes.
There are two caveats, however. First, make it clear to the user which keys are active and what they do. Second, do not assign a key combination that's already used for something else. A key combination that you assign to a macro takes precedence over the built-in shortcut keys. For example, Ctrl+S is a built-in Excel shortcut key used to save the current file. If you assign this key combination to a macro, you lose the capability to save the file with Ctrl+S. Remember that shortcut keys are case sensitive, so you can use a combination such as Ctrl+Shift+S.
Creating custom dialog boxes
Anyone who has used a personal computer for any length of time is undoubtedly familiar with dialog boxes. Consequently, custom Excel dialog boxes can play a major role in the user interfaces that you design for your applications. Figure 1.2 shows an example of a custom dialog box.
Screenshot of a custom dialog box created with Excel's UserForm feature.FIGURE 1.2 A dialog box created with Excel's UserForm feature
A custom dialog box is known as a UserForm. A UserForm can solicit user input, get a user's options or preferences, and direct the flow of your entire application. The elements that make up a UserForm (buttons, drop-down lists, check boxes, and so on) are called controls—more specifically, ActiveX controls. Excel provides a standard assortment of ActiveX controls, and you can also incorporate third-party controls.
After adding a control to a dialog box, you can link it to a worksheet cell so that it doesn't require any macros (except a simple macro to display the dialog box). Linking a control to a cell is easy, but it's not always the best way to get user input from a dialog box. Most of the time, you want to develop VBA macros that work with your custom dialog boxes.
Arrow_icon We cover UserForms in detail in Part III.
Using ActiveX controls on a worksheet
Excel also lets you add UserForm ActiveX controls to a worksheet's drawing layer (an invisible layer on top of a sheet that holds pictures, charts, and other objects). Figure 1.3 shows a simple worksheet model with several UserForm controls inserted directly in the worksheet. This sheet contains the following ActiveX controls: a CheckBox, a ScrollBar, and two sets of OptionButtons. This workbook uses no macros. Rather, the controls are linked to worksheet cells.
Screenshot of a simple worksheet model with several UserForm controls inserted directly in the worksheet, and the sheet contains the following ActiveX controls: a CheckBox, a ScrollBar, and two sets of OptionButtons.FIGURE 1.3 You can add UserForm controls to worksheets and link them to cells.
ON THE WEB
This workbook is available on this book's website. The file is named worksheet controls.xlsx.
Perhaps the most common control is a CommandButton. By itself, a CommandButton doesn't do anything, so you need to attach a macro to each CommandButton.
Using dialog box controls directly in a worksheet often eliminates the need for custom dialog boxes. You can often greatly simplify the operation of a spreadsheet by adding a few ActiveX controls (or form controls) to a worksheet. These ActiveX controls let the user make choices by operating familiar controls rather than making entries in cells.
Access these controls by using the Developer ➪ Controls ➪ Insert command (see Figure 1.4). If the Developer tab isn't on the Ribbon, add it by using the Customize Ribbon tab of the Excel Options dialog box.
Screenshot of using the ribbon to add controls to a worksheet.FIGURE 1.4 Using the Ribbon to add controls to a worksheet
The controls come in two types: form controls and ActiveX controls. Both sets of controls have their advantages and disadvantages. Generally, form controls are easier to use, but ActiveX controls are a bit more flexible. Table 1.1 summarizes these two classes of controls.
TABLE 1.1 ActiveX Controls versus Form Controls
Executing the development effort
After you identify user needs, determine the approach you'll take to meet those needs, and decide on the components that you'll use for the user interface. Next, it's time to get down to the nitty-gritty and start creating the application. This step, of course, constitutes a great deal of the total time you spend on a particular project.
How you go about developing the application depends on your personal style and the nature of the application. Except for simple fill-in-the-blanks template workbooks, your application will probably use macros. Creating macros in Excel is easy, but creating good macros is difficult.
Concerning Yourself with the End User
In this section, we discuss the important development issues that surface as your application becomes more and more workable and as the time to package and distribute your work grows nearer.
Testing the application
How many times have you used a commercial software application, only to have it bomb out on you at a crucial moment? Most likely, the problem was caused by insufficient testing that didn't catch all of the bugs. All nontrivial software has bugs, but in the best software, the bugs are simply more obscure. As you'll see, you sometimes must work around the bugs in Excel to get your application to perform properly.
After you create your application, you need to test it. Testing is one of the most crucial steps; it's not uncommon to spend as much time testing and debugging an application as you did creating it. Actually, you should be doing a great deal of testing during the development phase. After all, whether you're writing a VBA routine or creating formulas in a worksheet, you want to make sure that the application is working the way it's supposed to work.
Like standard compiled applications, spreadsheet applications that you develop are prone to bugs. A bug can be defined as (1) something that does happen but shouldn't happen while a program (or application) is running, or (2) something that doesn't happen when it should happen. Both species of bugs are equally nasty, and you should plan on devoting a good portion of your development time to testing the application under all reasonable conditions and fixing any problems that you find.
It's important to test thoroughly any spreadsheet application that you develop for others. And depending on its eventual audience, you may want to make your application bulletproof. In other words, try to anticipate all the errors and screw-ups that could possibly occur and make concerted efforts to avoid them—or, at least, to handle them gracefully. This foresight not only helps the end user but also makes it easier on you and protects your reputation. Also, consider using beta testing—your end users are likely candidates because they're the ones who will be using your product. (See the upcoming sidebar What about beta testing?
)
Although you can't conceivably test for all possibilities, your macros should be able to handle common types of errors. For example, what if the user enters a text string instead of a numeric value? What if the user tries to run your macro when a workbook isn't open? What if the user cancels a dialog box without making any selections? What happens if the user presses Ctrl+F6 and jumps to the next window? When you gain experience, these types of issues become very familiar, and you account for them without even thinking.
What about beta testing?
Software manufacturers typically have a rigorous testing cycle for new products. After extensive internal testing, the pre-release product is usually sent to a group of interested users for beta testing. This phase often uncovers additional problems that are usually corrected before the product's final release.
If you're developing an Excel application that more than a few people will use, you may want to consider a beta test. This test enables your intended users to use your application in its proposed setting on different hardware (usually).
The beta period should begin after you've completed all of your own testing and you feel that the application is ready to distribute. You'll need to identify a group of users to help you. The process works best if you distribute everything that will ultimately be included in your application: user documentation, the installation program, help, and so on. You can evaluate the beta test in a number of ways, including face-to-face discussions, email, questionnaires, and phone calls.
You almost always become aware of problems that you need to correct or improvements that you need to make before you undertake a widespread distribution of the application. Of course, a beta-testing phase takes additional time, and not all projects can afford that luxury.
Making the application bulletproof
If you think about it, destroying a spreadsheet is fairly easy. Erasing one critical formula or value can cause errors throughout the entire worksheet—and perhaps even other dependent worksheets. Even worse, if the damaged workbook is saved, it replaces the good copy on disk. Unless a backup procedure is in place, the user of your application may be in trouble, and you will probably be blamed for it.
Obviously, you can easily see why you need to add some protection when users—especially novices—will be using your worksheets. Excel provides several techniques for protecting worksheets and parts of worksheets.
Lock specific cells You can lock specific cells (by using the Protection tab in the Format Cells dialog box) so that users can't change them. Locking takes effect only when the document is protected with the Review ➪ Changes ➪ Protect Sheet command. The Protect Sheet dialog box has options that allow you to specify which actions users can perform on a protected sheet (see Figure 1.5).
Screenshot of the protect sheet dialog box with options that allow you to specify which actions users can perform on a protected sheet.FIGURE 1.5 Using the Protect Sheet dialog box to specify what users can and can't do
Hide the formulas in specific cells You can hide the formulas in specific cells (by using the Protection tab in the Format Cells dialog box) so that others can't see them. Again, hiding takes effect only when the document is protected by choosing the Review ➪ Changes ➪ Protect Sheet command.
Protect an entire workbook You can protect an entire workbook—the structure of the workbook, the window position and size, or both. Use the Review ➪ Protect ➪ Protect Workbook command for this purpose.
Lock objects on the worksheet Use the Properties section in the task pane to lock objects (such as shapes) and prevent them from being moved or changed. To access this section of the task pane, right-click the object and choose Size and Properties. Locking objects takes effect only when the document is protected using the Review ➪ Protect ➪ Protect Sheet command. By default, all objects are locked.
Hide rows, columns, sheets, and documents You can hide rows, columns, sheets, and entire workbooks. Doing so helps prevent the worksheet from looking cluttered, and it also provides some modest protection against prying eyes.
Designate an Excel workbook as read-only recommended You can designate an Excel workbook as read-only recommended (and use a password) to ensure that the file can't be overwritten with any changes. You make this designation in the General Options dialog box. Display this dialog box by choosing File ➪ Save As, choosing a directory, and then clicking the Tools button found on the Save As dialog box. Choose General Options to specify the appropriate password.
Assign a password You can assign a password to prevent unauthorized users from opening your file. Choose File ➪ Info ➪ Protect Workbook ➪ Encrypt with Password.
Use a password-protected add-in You can use a password-protected add-in, which doesn't allow the user to change anything on their worksheets.
Excel passwords are not foolproof
Be aware that Excel passwords can often be easily circumvented using commercially available password-breaking programs. Don't think of password protection as foolproof. Sure, it will be effective for the casual user. But if someone really wants to break your password, he or she probably can.
Making the application aesthetically appealing and intuitive
If you've used many different software packages, you've undoubtedly seen examples of poorly designed user interfaces, difficult-to-use programs, and just plain ugly screens. If you're developing spreadsheets for other people, you should pay particular attention to how the application looks.
How a computer program looks can make all the difference in the world to users, and the same is true of the applications that you develop with Excel. Beauty, however, is in the eye of the beholder. If your skills lean more in the analytical direction, consider enlisting the assistance of someone with a more aesthetic sensibility to provide help with design.
End users appreciate a good-looking user interface, and your applications will have a much more polished and professional look if you devote additional time to design and aesthetic considerations. An application that looks good demonstrates that its developer cared enough about the product to invest extra time and effort. Take the following suggestions into account:
Strive for consistency When designing dialog boxes, for example, try to emulate the look and feel of Excel's dialog boxes whenever possible. Be consistent with formatting, fonts, text size, and colors.
Keep it simple A common mistake that developers make is trying to cram too much information into a single screen or dialog box. A good rule is to present only one or two chunks of information at a time.
Break down input screens If you use an input screen to solicit information from the user, consider breaking it up into several, less-crowded screens. If you use a complex dialog box, you may want to break it up by using a MultiPage control, which lets you create a familiar tabbed dialog box.
Don't overdo color Use color sparingly. It's easy to overdo color and make the screen look gaudy.
Monitor typography and graphics Pay attention to numeric formats and use consistent typefaces, font sizes, and borders.
Evaluating aesthetic qualities is subjective. When in doubt, strive for simplicity and clarity.
Creating a user Help system
With regard to user documentation, it's a best practice to provide users with paper-based documentation or electronic documentation (or both). Providing electronic help is standard fare in Windows applications. Fortunately, your Excel applications can also provide help—even context-sensitive help. Developing help text takes quite a bit of additional effort, but for a large project it may be worth it.
Another point to consider is support for your application. In other words, who gets the phone call if the user encounters a problem? If you aren't prepared to handle routine questions, you need to identify someone who is. In some cases, you want to arrange it so that only highly technical or bug-related issues escalate to the developer.
Arrow_icon In Chapter 19, Providing Help for Your Applications,
we discuss several alternatives for providing help for your applications.
Documenting the development effort
Putting a spreadsheet application together is one thing. Making it understandable for other people is another. As with traditional programming, it's important that you thoroughly document your work. Such documentation helps if you need to go back to it (and you will), and it helps anyone else whom you might pass it onto.
How do you document a workbook application? You can either store the information in a worksheet or use another file. You can even use a paper document if you prefer. Perhaps the easiest way is to use a separate worksheet to store your comments and key information for the project. For VBA code, use comments liberally. (VBA text preceded with an apostrophe is ignored because that text is designated as a comment.) Although an elegant piece of VBA code can seem perfectly obvious to you today, when you come back to it in a few months, your reasoning may be completely obscured unless you use the VBA comment feature.
Distributing the application to the user
You've completed your project, and you're ready to release it to the end users. How do you go about distributing it? You can choose from many ways to distribute your application, and the method that you choose depends on many factors.
You could just hand over a download link or thumb drive, scribble a few instructions, and be on your way. Or, you may want to install the application yourself—but this approach isn't always feasible. Another option is to develop an official setup program that performs the task automatically. You can write such a program in a traditional programming language, purchase a generic setup program, or write your own in VBA.
Excel incorporates technology to enable developers to sign their applications digitally. This process is designed to help end users identify the author of an application, to ensure that the project has not been altered, and to help prevent the spread of macro viruses or other potentially destructive code. To sign a project digitally, you first apply for a digital certificate from a formal certificate authority (or you can self-sign your project by creating your own digital certificate). Refer to the Help system or the Microsoft website for additional information.
Updating the application when necessary
After you distribute your application, you're finished with it, right? You can sit back, enjoy yourself, and try to forget about the problems that you encountered (and solved) during development. In rare cases, yes, you may be finished. More often, however, the users of your application won't be completely satisfied. Sure, your application adheres to all of the original specifications, but things change. Seeing an application working often causes the user to think of other things that the application could be doing.
When you need to update or revise your application, you'll appreciate that you designed it well in the first place and that you fully documented your efforts.
Other Development Issues
You need to keep several other issues in mind when developing an application—especially if you don't know exactly who will be using the application. If you're developing an application that will have widespread use (a shareware application, for example), you have no way of knowing how the application will be used, what type of system it will run on, or what other software will be running concurrently.
The user's installed version of Excel
Although Excel 2019 is available, many large corporations are still using earlier versions of Excel. Unfortunately, there is no guarantee that an application developed for, say, Excel 2010 will work perfectly with later versions of Excel. If you need your application to work with a variety of Excel versions, the best approach is to work with the lowest version—and then test it thoroughly with all other versions.
Also, be aware of any security updates or new changes to Excel released with service packs (for stand-alone versions of Excel). If some of your users are on Office 365, be aware that Microsoft has adopted an agile release cycle, allowing it to release updates to Office 365 practically on a monthly basis. This is great news for those who love seeing new features added to Excel. It's not so great if you're trying to manage compatibility with your application. Although rare, some changes introduced in these releases can cause certain components of your application no longer to work as designed.
Arrow_icon Compatibility issues are discussed in Chapter 21, Understanding Compatibility Issues.
Language issues
Consider yourself fortunate if all of your end users have the English language version of Excel. Non-English versions of Excel aren't always 100 percent compatible, so that means additional testing on your part. In addition, keep in mind that two users can both be using the English language version of Excel yet use different Windows regional settings. In some cases, you may need to be aware of potential problems.
Arrow_icon We briefly discuss language issues in Chapter 21.
System speed
Although system speed and processing power has become less of an issue on modern PCs and devices, testing your application for performance and speed is still a recommended best practice. A procedure that executes almost instantaneously on your system may take several seconds to execute on another system. In the world of computers, several seconds may be unacceptable.
TIP
When you gain more experience with VBA, you'll discover that there are ways to get the job done and there are ways to get the job done fast. It's a good idea to get into the habit of coding for speed. Other chapters in this book can certainly help you out in this area.
Video modes
As you probably know, users' video displays vary widely. Higher-resolution displays and even dual displays are becoming increasingly common. Just because you have a super-high-resolution monitor, you can't assume that everyone else does.
Video resolution can be a problem if your application relies on specific information being displayed on a single screen. For example, if you develop an input screen that fills the screen in 1280 × 1024 mode, users with a 1024 × 768 display won't be able to see the whole input screen without scrolling or zooming.
Also, it's important to realize that a restored (that is, not maximized or minimized) workbook is displayed at its previous window size and position. In the extreme case, it's possible that a window saved by using a high-resolution display may be completely off the screen when opened on a system running in a lower resolution.
Unfortunately, you can't automatically scale things so that they look the same regardless of the display resolution. In some cases, you can zoom the worksheet (using the Zoom control in the status bar), but doing so reliably may be difficult. Unless you're certain about the video resolution that the users of your application will use, you should probably design your application so that it works with the lowest common denominator—800 × 600 or 1024 × 768 mode.
As you will discover later in the book, you can determine the user's video resolution by using Windows API calls from VBA. In some cases, you may want to adjust things programmatically, depending on the user's video resolution.
CHAPTER 2
Introducing Visual Basic for Applications
IN THIS CHAPTER
Using Excel's macro recorder
Working with the Visual Basic Editor
Understanding the Excel Object Model
Diving into the Range object
Knowing where to turn for help
Getting a Head Start with the Macro Recorder
A macro is essentially Visual Basic for Applications (VBA) code that you can call to execute any number of actions. In Excel, macros can be written or recorded.
Excel programming terminology can be a bit confusing. A recorded macro is technically no different from a VBA procedure that you create manually. The terms macro and VBA procedure are often used interchangeably. Many Excel users call any VBA procedure a macro. However, when most people think of macros, they think of recorded macros.
Recording a macro is like programming a phone number into your smartphone. First you manually enter and save a number. Then when you want, you can redial the number with the touch of a button. Just like on a smartphone, you can record your actions in Excel while you perform them. While you record, Excel gets busy in the background, translating and storing your keystrokes and mouse clicks to VBA code. After a macro is recorded, you can play back those actions any time you want.
The absolute best way to become familiar with VBA, without question, is simply to turn on the macro recorder and record some of the actions that you perform in Excel. This approach is a quick way to learn the relevant VBA syntax for a task.
In this section, you'll explore macros and learn how you can use the macro recorder to start familiarizing yourself with VBA.
Creating your first macro
To start recording your first macro, you first need to find the macro recorder, which is on the Developer tab. Unfortunately, Excel comes out of the box with the Developer tab hidden—you may not see it on your version of Excel at first. To display this tab, follow these steps:
Choose File ➪ Excel Options.
In the Excel Options dialog box, select Customize Ribbon.
In the list box on the right, place a check mark next to Developer.
Click OK to return to Excel.
Now that you have the Developer tab showing in the Excel Ribbon, you can start up the macro recorder by selecting the Record Macro command found in the Code group on the Developer tab. This activates the Record Macro dialog box, as shown in Figure 2.1.
Screenshot of the record macro dialog box, with Macro name, Shortcut key, Store macro in, and Description.FIGURE 2.1 The Record Macro dialog box
NOTE
Note that you can also get to the Macro Recorder by selecting View ➪ Macros ➪ Macros ➪ Record Macros. However, if you plan to work with VBA macros, you'll want to make sure that the Developer tab is visible in order to gain access to the full gamut of developer features.
Here are the four parts of the Record Macro dialog box:
Macro Name This should be self-explanatory. Excel gives a default name to your macro, such as Macro1, but you should give your macro a name more descriptive of what it actually does. For example, you might name a macro that formats a generic table as FormatTable.
Shortcut Key Every macro needs an event, or something to happen, for it to run. This event can be a button press, a workbook opening, or, in this case, a keystroke combination. When you assign a shortcut key to your macro, entering that combination of keys triggers your macro to run. This is an optional field.
Store Macro In This Workbook is the default option. Storing your macro in This Workbook simply means that the macro is stored along with the active Excel file. The next time you open that particular workbook, the macro is available to run. Similarly, if you send the workbook to another user, that user can run the macro as well (provided the macro security is properly set by your user—more on that later in this chapter).
Description This is an optional field, but it can come in handy if you have numerous macros in a workbook or if you need to give a user a more detailed description about what the macro does. The description is also useful for distinguishing one macro from another when you have multiple workbooks open or you have macros stored in the Personal Macro Workbook.
With the Record Macro dialog box open, follow these steps to create a simple macro that enters your name into a worksheet cell:
Enter a new single-word name for the macro to replace the default Macro1 name. A good name for this example is MyName.
Assign the shortcut key Ctrl+Shift+N to this macro by entering uppercase N in the edit box labeled Shortcut Key.
Click OK to close the Record Macro dialog box and begin recording your actions.
Type your name into the active cell and press Enter.
Choose Developer ➪ Code ➪ Stop Recording. Alternatively, you can click the Stop Recording icon in the status bar (the square icon on left side of the status bar).
Examining your macro
Excel stored your newly recorded macro in a new module that it created automatically and named Module1. To view the code in this module, you must activate the Visual Basic Editor. You can activate the VB Editor in either of two ways:
Press Alt+F11.
Choose Developer ➪ Code ➪ Visual Basic.
In the VB Editor, the Project window displays a list of all open workbooks and add-ins. This list is displayed as a tree diagram on the left of the screen, which you can expand or collapse. The code that you recorded previously is stored in Module1 in the current workbook. When you double-click Module1, the code in the module appears in the Code window.
NOTE
If you don't see a Project window in the VB Editor, you can activate it by going up to the menu and selecting View ➪ Project Explorer. Alternatively, you can use the keyboard shortcut Ctrl+R.
The macro should look something like this:
Sub MyName() '' MyName Macro '' Keyboard Shortcut: Ctrl+Shift+N ActiveCell.FormulaR1C1 = Michael Alexander
End Sub
The macro recorded is a Sub procedure that is named MyName. The statements tell Excel what to do when the macro is executed.
Notice that Excel inserted some comments at the top of the procedure. These comments are some of the information that appeared in the Record Macro dialog box. These comment lines (which begin with an apostrophe) aren't really necessary, and deleting them has no effect on how the macro runs. If you ignore the comments, you'll see that this procedure has only one VBA statement.
ActiveCell.FormulaR1C1 = Michael Alexander
This single statement causes the name you typed while recording to be inserted into the active cell.
Testing your macro
Before you recorded this macro, you set an option that assigned the macro to the Ctrl+Shift+N shortcut key combination. To test the macro, return to Excel by using either of the following methods:
Press Alt+F11.
Click the View Microsoft Excel button on the standard toolbar in the VB Editor window.
When Excel is active, activate a worksheet. (It can be in the workbook that contains the VBA module or in any other workbook.) Select a cell and press Ctrl+Shift+N. The macro immediately enters your name into the cell.
NOTE
In the preceding example, notice that you selected your target cell before you started recording your macro. This step is important. If you select a cell while the macro recorder is turned on, the actual cell that you selected will be recorded into the macro. In such a case, the macro would always format that particular cell, and it would not be a general-purpose macro.
Editing your macro
After you record a macro, you can make changes to it. For example, assume that you want your name to be bold. You could re-record the macro, but this modification is simple, so editing the code is more efficient. Press Alt+F11 to activate the VB Editor window. Then activate Module1 and insert ActiveCell.Font.Bold = True, as demonstrated in the following sample code:
ActiveCell.Font.Bold = True
The edited macro appears as follows:
Sub MyName() '' MyName Macro '' Keyboard Shortcut: Ctrl+Shift+N ActiveCell.Font.Bold = True ActiveCell.FormulaR1C1 = Michael Alexander
End Sub
Test this new macro, and you'll see that it performs as it should.
Comparing absolute and relative macro recording
Now that you've read about the basics of the macro recorder interface, it's time to go deeper and begin recording a more complex macro. The first thing you need to understand before you begin is that Excel has two modes for recording: absolute reference and relative reference.
Recording macros with absolute references
Excel's default recording mode is in absolute reference. As you may know, the term absolute reference is often used in the context of cell references found in formulas. When a cell reference in a formula is an absolute reference, it does not automatically adjust when the formula is pasted to a new location.
The best way to understand how this concept applies to macros is to try it. Open the Chapter 2 Sample.xlsm file and record a macro that counts the rows in the Branchlist worksheet. (See Figure 2.2.)
Screenshot of pretotaled worksheet that contains two tables, with details such as Region, Market, and Branch.FIGURE 2.2 Your pretotaled worksheet containing two tables
NOTE
The sample dataset used in this chapter can be found on this book's companion website. See this book's introduction for more on the companion website.
Follow these steps to record the macro:
Before recording, make sure that cell A1 is selected.
Select Record Macro from the Developer tab.
Name the macro AddTotal.
Choose This Workbook in the Store Macro In drop-down.
Click OK to start recording.
At this point, Excel is recording your actions. While Excel is recording, perform the following steps:
Select cell A16, and type Total in the cell.
Select the first empty cell in Column D (D16), type = COUNTA(D2:D15), and then press Enter. This gives a count of branch numbers at the bottom of column D. The COUNTA function is used to catch any branch numbers stored as text.
Click Stop Recording on the Developer tab to stop recording the macro.
The formatted worksheet should look like something like the one in Figure 2.3.
Screenshot of post-totaled worksheet, with details such as Region, Market, and Branch.FIGURE 2.3 Your post-totaled worksheet
To see your macro in action, delete the total row that you just added and play back your macro by following these steps:
Select Macros from the Developer tab.
Find and select the AddTotal macro that you just recorded.
Click the Run button.
If all goes well, the macro plays back your actions perfectly and gives your table a total. Here's the thing: no matter how hard you try, you can't make the AddTotal macro work on the second table.