Cover of the summary of “Excel VBA Programming For Dummies”

Book summary “Excel VBA Programming For Dummies”: summary

John Walkenbach

4,325 words · 25 min read

You spend hours every week performing the same repetitive chores in Excel. Copying data across sheets, formatting identical reports, and fixing formula errors drain your time and energy. Manual spreadsheet labor slows your workflow and introduces human mistakes into critical business numbers.

Summary text

4,325 words · 25 min read

Introduction

You spend hours every week performing the same repetitive chores in Excel. Copying data across sheets, formatting identical reports, and fixing formula errors drain your time and energy. Manual spreadsheet labor slows your workflow and introduces human mistakes into critical business numbers. You know there has to be a faster way to handle these tedious operations without starting from scratch every single day.

Visual Basic for Applications acts as a hidden programming powerhouse built directly into Excel. John Walkenbach shows you how to harness this built-in language to turn Excel into an intelligent assistant that executes complex tasks in seconds. You do not need a computer science degree to start writing code. The central idea of this book is that anyone can transition from a frustrated spreadsheet user to an efficient automation engineer by breaking down programming into logical, manageable steps.

The book guides you through a clear learning path designed for practical results. You begin by recording your first automated macros and exploring the development environment behind the scenes. You learn to control the fundamental building blocks of code, manage program flow, and handle unexpected errors smoothly. As you progress, you discover how to build interactive dialog boxes, construct custom worksheet functions, and package your finished tools into professional add-ins.

You might wonder as you begin this journey:

  • How do you turn a series of manual clicks into reusable code?
  • What separates a sub procedure from a function procedure?
  • How do you reference specific cells and ranges dynamically?
  • When should you use conditional logic and loops to control execution?
  • How do you build custom user interfaces and forms?

You will find concrete answers to all these questions and more across the chapters that follow.

1. Introduction to VBA

Excel stands as a powerful tool for data analysis and management. Yet many tasks require endless clicking and formatting. You can eliminate this manual labor by tapping into the programming language hidden inside your spreadsheet software.

Visual Basic for Applications acts as a powerful programming language built directly into Excel to automate routine commands and eliminate manual spreadsheet labor.

What Is VBA

Visual Basic for Applications (VBA) is a built-in programming language included at no extra charge with Microsoft Office applications. It is designed to control and automate Excel tasks.

John Walkenbach compares VBA to an intelligent robot that operates Excel very fast and accurately based on special codes provided by the user. This built-in system acts as a set of instructions for Excel to perform repetitive or complex sequences of commands automatically. You are freed from manual labor and errors are significantly reduced.

Why Bother with VBA

Learning VBA programming significantly enhances software productivity. It makes you more marketable and allows you to perform tasks in Excel that are otherwise impossible.

While mastering VBA requires an initial time investment, it ultimately saves substantial time. You can automate:

  • reports;
  • repetitive operations across multiple workbooks;
  • custom commands.

Macro Security Settings

Excel includes rigorous security settings to prevent malicious macros from executing. You must configure how workbooks containing macros are handled before you run custom code.

Microsoft provides several options in the Trust Center to manage security risks associated with executable code:

  • disable all macros with notification;
  • disable all macros without notification;
  • enable all macros;
  • trust specific locations.

2. Getting Started with Macros

You can jumpstart your programming journey by recording manual actions into reusable code and saving workbooks in macro-enabled formats.

Developer Tab Setup

To begin programming in Excel 2010 or 2013, the hidden Developer tab must first be unhidden through the Excel Ribbon customization menu. You must right-click the Ribbon, choose Customize the Ribbon, and check the box for the Developer tab. This action grants you direct access to macro recording and Visual Basic tools.

Macro Recording Process

Excel includes a built-in macro recorder that monitors user actions and automatically converts them into corresponding VBA code statements. By launching the Record Macro dialog box, giving the macro a descriptive name, and optionally assigning a shortcut key, you can record manual steps for later automated playback.

Creating the NameAndTime macro records typing a name, inserting the NOW formula, converting it to a value, and applying 16-point bold formatting.

Macro File Formats

Workbooks containing VBA macros must be saved using a specialized macro-enabled file extension rather than the default format. If you attempt to save a workbook containing code in a standard format, Excel displays a warning and requires the format to be changed to support executable procedures.

You must choose the correct file type in the Save As dialog box to prevent code loss:

  • XLSX extension for standard workbooks without code;
  • XLSM extension for workbooks containing VBA macros.

3. Visual Basic Editor Basics

The Visual Basic Editor provides a dedicated development environment where you write, edit, and organize your procedures and modules.

VBE Overview

You can activate the Visual Basic Editor by pressing Alt+F11 or by using the Developer tab in Excel. The VBE cannot run independently and requires Excel to be active at all times.

The interface features a customizable environment with several key components:

  • menu bar
  • toolbars
  • Project window
  • Code windows
  • Immediate window

VBA Code Entry

You can introduce VBA code into a module through direct entry, using the macro recorder, or copying and pasting from existing modules. Code modules can store declarations, Sub procedures, and Function procedures. A single module can hold approximately 64,000 characters of VBA code.

The author walks through creating a GuessName procedure that uses user names and message boxes, and a TenByTen macro that formats an inserted worksheet. Running the TenByTen macro example leaves exactly 10 visible rows and 10 visible columns.

VBE Customization

The VBE offers extensive customization options via its Tools Options dialog box to aid code readability and developer productivity. Settings like Auto List Members and Auto Quick Info provide IntelliSense-like assistance and argument prompts while you type.

Other configuration settings control important coding behaviors:

  • indentation
  • syntax checking
  • explicit variable requirements

4. The Excel Object Model

Excel organizes its entire application architecture into a hierarchical object model controlled through properties and methods.

Object Hierarchy

Excel programming relies on an object-oriented hierarchy where the Application object sits at the top and contains lower-level objects. The object model organizes Excel into containers and contents, such as workbooks containing worksheets, which in turn contain ranges and other elements. Fully qualified references explicitly map out this exact hierarchy using dot operators.

The author compares Excel's object hierarchy to a fast-food chain where restaurants contain kitchens, and kitchens contain specific equipment like stoves and ventilation fans. You navigate through these levels by chaining objects together in your code.

Collections

Collections are plural-named objects representing groups of similar objects that allow developers to manage multiple elements simultaneously. Collections such as Workbooks, Worksheets, and Sheets group related objects together.

You can identify and work with these grouping structures using specific naming conventions:

  • Workbooks
  • Worksheets
  • Sheets

Individual items can be referenced from a collection using their name in quotation marks or their numeric index.

Properties and Methods

Meaningful VBA tasks are accomplished by reading or changing object properties or by executing object methods to perform actions. Properties describe an object's attributes like appearance, visibility, or values, whereas methods trigger actions that can modify those properties or execute operations. Both individual objects and collections support specific sets of properties and methods.

The ShowValue macro reads the Value property of cell A1 into a message box, and the ChangeValue macro assigns the number 994.92 to cell A1. The ClearRange macro uses the ClearContents method to erase a range of cells where 12 cells are cleared in the ClearRange macro example.

5. Sub and Function Procedures

VBA divides tasks between Sub procedures that execute actions and Function procedures that perform calculations and return values.

A Sub procedure acts like a command to execute actions in Excel without returning a value. A Function procedure works similarly to built-in worksheet functions like SUM or VLOOKUP. It takes arguments, performs calculations, and returns a single value or an array. Function procedures can accept up to 255 arguments maximum.

Procedure Types

You can use two primary types of procedures in your code. Each serves a distinct purpose in your automation workflow.

Naming Conventions

VBA procedure names must follow strict rules and conventions to avoid syntax errors and ensure clarity. Names must begin with a letter and cannot contain spaces or periods. You cannot use specific punctuation characters like #, $, %, &, @, ^, *, or !. A procedure name has a maximum length of 255 characters maximum. VBA is not case-sensitive regarding these names.

Naming a procedure Hairball Harris is technically allowed by VBA, but combining a verb and a noun like ProcessData or PrintReport is recommended.

Executing Procedures

Sub procedures that do not require arguments can be run using many methods. You can choose the approach that best fits your workflow.

  • Press the F5 key in the Visual Basic Editor;
  • open Excel's Macro dialog box via Alt+F8;
  • assign shortcut keys;
  • click worksheet buttons or shapes;
  • call the code from other procedures;
  • use the Quick Access Toolbar or custom Ribbon items;
  • trigger specific workbook events;
  • run commands directly from the Immediate window.

Creating a button using Form Controls and linking it to the ShowCubeRoot macro allows users to execute the code simply by clicking the button.

Function procedures have restricted execution methods and must be called either from another procedure or directly inside a worksheet formula. Unlike Sub procedures, functions cannot be executed via shortcut keys, buttons, or the Macro dialog box's normal run list. They return results by assigning the calculated value directly to the function's own name.

The CubeRoot function takes a number argument and calculates its cube root, returning that calculated value back to the calling routine or worksheet formula. Entering the formula =CubeRoot(1728) into a worksheet cell executes the custom VBA function and displays the result 12, where 1728 is tested as an argument in a worksheet formula to return 12.

6. Using the Macro Recorder

The macro recorder translates your mouse clicks and keystrokes into VBA statements, allowing absolute or relative reference recording.

You can use the macro recorder as a digital video equivalent for Excel tasks. It stores actions in a VBA module and helps you generate code snippets to learn from.

Recorder Basics

The macro recorder is useful for recording simple tasks. It cannot record Function procedures or handle loops and conditional statements.

You can start recording and stop using the Stop Recording button. Common storage destinations include:

  • the Active Workbook;
  • a New Workbook;
  • the Personal Macro Workbook.

Recording the insertion of month names generates explicit Range selection and ActiveCell formula assignment statements.

Absolute Versus Relative

The macro recorder can operate in either absolute or relative reference mode depending on how cell destinations should be handled during playback. Absolute recording mode records exact cell addresses so the macro always acts on the exact same cells regardless of the active selection. Relative recording mode records offsets from the active cell so the macro executes relative to wherever your cursor is currently placed.

You toggle relative recording by clicking the Use Relative References button. The resulting code uses the Offset method instead of static cell addresses.

Recording the entry of month names in absolute mode always targets cells B1 to D1. Relative mode inserts them starting at whatever cell is currently active.

Cleaning Recorded Code

Recorded macro code is often inefficient and contains a significant amount of extraneous property settings that you should clean up manually. Simple UI commands can cause the macro recorder to generate extensive blocks of code capturing numerous unchanged properties. You can dramatically streamline and accelerate macros by deleting irrelevant lines and removing unnecessary object constructs.

Changing the page orientation to landscape generates dozens of lines setting print headers, footers, and margins, which can be reduced to a single line changing the Orientation property. The recorder also generates unnecessary settings like a 600 print quality setting and a 100 zoom level property during page setup. You can remove this macro-recording overkill and simplify With-End With constructs to make your modules much easier to read and maintain.

7. Essential VBA Language Elements

Writing robust code requires mastering variable declarations, explicit scoping rules, dynamic arrays, and efficient range references.

Variables and Scope

Unclaimed variables default to the Variant data type. This consumes more memory and slows down execution because VBA must perform runtime checks. Placing Option Explicit at the top of a module forces declaration of all variables.

A misspelled variable like CurentRate instead of CurrentRate causes silent logic failures unless Option Explicit is enabled. You can set the Visual Basic Editor to include this instruction automatically by selecting Require Variable Definition.

  • 255 characters is the maximum length for a variable name.

A variable's scope determines which procedures and modules can access it. Its lifetime dictates when it is cleared from memory. Variables can have procedure-only scope using Dim or Static. They can have module-only scope using Dim or Private in the declarations section. They can also have global scope across all modules using the Public keyword.

Declaring a Static Counter inside a Sub MySub() procedure keeps track of executions across multiple runs without resetting until the workbook is closed.

Working with Arrays

Arrays store groups of variables under a common name. They can be fixed-size or dynamic using ReDim and Preserve keywords. Arrays are declared with specific upper and lower bounds or via Option Base 1. Dynamic arrays allow resizing during runtime. The Preserve keyword prevents data loss when expanding dimensions.

  • 60 dimensions is the maximum allowed for a VBA array.
  • 100 elements declared in Dim MyArray(1 To 100) As Integer.

Declaring Dim MyArray(1 To 9, 1 To 9) As Integer creates a two-dimensional matrix suitable for holding numbers in a Sudoku puzzle.

Range Objects and References

The Range object is the core container for cells in a worksheet. You can reference it using addresses, named ranges, or properties like Cells and Offset. Range references must be enclosed in quotes unless using properties like Cells(row, column) or Offset(rowOffset, columnOffset). Unqualified ranges default to the active worksheet.

  • 17,179,869,184 cells is the maximum number of cells in a worksheet spanning A1:XFD1048576.

8. Controlling Program Flow

You can direct how your code executes by using conditional If-Then statements, Select Case branches, and flexible looping structures.

If-Then Decisions

The If-Then structure is VBA's primary conditional control mechanism. It executes statements based on whether a tested condition is true. It supports single-line evaluations and block structures with End If. It also supports multi-branch evaluations using ElseIf clauses to test multiple conditions efficiently. Nested If-Then-Else statements handle complex logic trees.

You can record a greeting procedure using GreetMe variants to display messages depending on the system time. The code evaluates numeric time serial values. In Excel time serial values, 0.5 represents noon and 0.75 represents 6:00 PM.

Select Case Structures

The Select Case structure offers a cleaner alternative to multiple If-Then-Else branches when a decision involves three or more options. The structure evaluates a single variable against various Case clauses. It exits immediately once a matching condition is executed.

Using Select Case in ShowDiscount3 evaluates quantity ranges and assigns corresponding discount percentages. The structure checks specific value bands:

  • 0 to 24 for the first quantity discount tier;
  • 25 to 49 for the second tier;
  • 50 to 74 for the third tier;
  • 75 or greater for the maximum discount tier.

Looping Mechanisms

A For-Next loop repeats a block of statements a specified number of times. A counter variable increments or decrements with each iteration. You can customize loop increments using a Step value. You can prematurely exit loops using the Exit For statement or nest loops inside one another.

You can run a TimeTest loop of 100 million iterations to compare computer execution speeds against manual coin flipping. This benchmark produces an 8.03 seconds runtime on the author's system. You can also deploy a smaller loop of 1,000 iterations used to sum positive integers.

The For Each-Next loop structure is specifically designed to iterate through every object within a collection. Collections include open workbooks, worksheets, or cell ranges. This loop simplifies tasks like evaluating all worksheets in a workbook. It inspects every cell in a used range without relying on numeric index counters. You can target all objects by declaring an object variable to process items dynamically.

9. Events and Error Handling

Automatic event handlers and strategic error-trapping mechanisms allow your macros to respond to user actions and avoid abrupt crashes.

Procedures responding to Excel events must be placed in specific object code modules rather than standard modules. Workbook-related events require code in the ThisWorkbook object module. Worksheet-related events go into specific Sheet object modules. If placed in a standard module, the event handler will fail silently without error messages.

A Worksheet_Change macro that logs timestamps in column A must reside specifically in that worksheet's code module.

The On Error statement allows developers to intercept run-time errors and bypass Excel's default messages. Using On Error GoTo redirects execution to an error-handling label. On Error Resume Next ignores errors entirely. You must include Exit Sub before the error label to prevent accidental execution.

An input macro for calculating square roots traps negative numbers and type mismatches by jumping to a custom error message.

The VBA built-in debugger provides sophisticated tools like breakpoints, the Immediate window, and the Locals window to inspect and fix code. Breakpoints suspend code execution in Break mode. This allows you to step through code line by line with F8, examine variables via tooltips, or evaluate expressions in the Immediate window.

A developer sets a breakpoint by pressing F9 and uses the Locals window to inspect all local variables without manually adding watches.

  • Break code execution using Break mode to inspect line-by-line operations.
  • Evaluate expressions directly inside the Immediate window.
  • Monitor variable values without adding watches via the Locals window.
  • Test iteration states using sample loops set at 900 cycles.

10. Advanced Programming Examples

Optimizing your code execution speed and avoiding unnecessary range selections will transform sluggish macros into lightning-fast routines.

Avoiding Selection

VBA code executes faster and cleaner when it operates on ranges directly without selecting them first. Recording actions like copying or cutting often generates redundant code that selects sheets and ranges. By supplying destination arguments directly to methods like Copy or Cut, macros perform operations in a single statement. This avoids shifting the active cell pointer.

Replacing a multi-line recorded copy macro with a concise single-line statement such as Range("A1:A5").Copy Range("B1") eliminates unnecessary selection and clearing of the copy mode.

Efficient Looping

Looping through entire rows or columns cell-by-cell significantly degrades macro performance. You must process only relevant subsets. Iterating over every cell in a selected row or column forces Excel to process 1,048,576 cells in a single Excel column. Utilizing methods like SpecialCells or intersecting the selection with the worksheet's used range ensures that code targets only non-blank populated cells.

Using the SpecialCells method with xlConstants and xlFormulas allows a macro to quickly apply bold formatting to positive numbers. It completely skips blank cells across an entire selection.

  • Avoid selecting ranges before performing operations.
  • Process only non-blank populated cells instead of entire columns.
  • Use the SpecialCells method to target constants and formulas directly.

Macro Speed Tips

Disabling visual screen updates and automatic calculations dramatically accelerates the execution speed of intensive macros. When Excel renders on-screen movements and recalculates complex formulas during every loop iteration, execution slows down. Disabling these background processes and alert messages allows the application to run tasks uninterrupted until completion.

Inserting Application.ScreenUpdating = False before running a nested loop that fills a grid of 50 rows by 50 columns used in a demonstration fill range macro prevents the screen from flashing. This completes the operation much faster.

11. Custom Dialog Boxes and UserForms

When a VBA macro requires multiple choices or more information than a message box can provide, you can create a Graphical User Interface. This approach lets you design a tailored environment for data collection.

You can build fully interactive custom dialog boxes using UserForms, toolbox controls, and event-handler subroutines.

A UserForm is an object that functions as a custom dialog box to collect necessary input from you before a macro continues running. The macro pauses when the form is shown using the Show method. It resumes execution after you close the dialog box.

UserForm Basics

You can manage the layout, dimensions, and properties of a UserForm directly within the development interface. Setting properties carefully ensures your interface looks professional and remains intuitive for anyone entering data.

Toolbox Controls

The VBE provides a floating Toolbox containing a wide variety of controls that can be dragged onto a UserForm to build interactive dialog boxes. You can populate your form with standard interface elements designed for specific input tasks.

  • Label controls display static instructional text.
  • TextBox controls gather typed information.
  • ComboBox and ListBox controls present selection choices.
  • CheckBox and OptionButton controls offer binary options.
  • Frame controls group related options together.
  • CommandButton controls trigger actions.
  • RefEdit controls allow range selections.

Writing Code for Forms

UserForm controls execute specific event-handler subroutines stored in the form's Code window when you interact with them. You can press the F7 key to view the Code window and write the necessary instructions.

When you click a button or interact with a control, VBA triggers an event handler named after the control combined with the event name, such as CommandButton_Click. These procedures dictate how the application responds to user inputs before you Unload the form from memory.

12. Creating Custom Functions and Add-Ins

Expanding Excel capabilities involves writing custom user-defined functions and packaging your macros into professional add-in files.

Excel 2013 contains 450 predefined worksheet functions available for calculations. You can extend this library by writing custom worksheet functions stored in standard VBA modules.

A Function procedure is passive and returns a value rather than executing actions on worksheet objects. You can call these procedures directly within spreadsheet formulas.

  • Pass cell references as arguments
  • Include ranges, constants, or expressions
  • Locate your formulas in the User Defined category

Custom Worksheet Functions

A custom Commission function can compute sales payouts by evaluating sales tiers without hard-coding complex worksheet formulas.

You can also create wrapper functions that simplify long native formulas or combine multiple operations into a single call.

Optional Arguments

Custom VBA functions can handle optional arguments and be configured as volatile to recalculate automatically. Optional arguments are preceded by the Optional keyword and assigned a default value.

Developers can make a function volatile by invoking Application.Volatile True so that it updates whenever the worksheet recalculates.

The DrawOne function randomly selects a cell from an input range and can be made volatile based on an optional Recalc argument. You often use 0 or 1 as default indicator values for optional recalculation parameters.

Creating Add-Ins

Workbooks containing useful macros or custom functions can be converted into professional add-ins with XLAM extensions. An add-in is a hidden workbook whose IsAddin property is set to True. This means its sheets cannot be viewed by casual users.

Add-ins make custom functions available across all workbooks without requiring workbook name qualifiers. You can manage them programmatically through the AddIns collection.

The Change Case text conversion utility can be packaged as an add-in and accessed via right-click shortcut menus.

Conclusion

Mastering Visual Basic for Applications transforms Excel from a static spreadsheet calculator into a dynamic application development platform. You can eliminate tedious manual routines, build tailored interfaces, and construct sophisticated automated solutions that save time and reduce errors. The core programming concepts, object references, and user interface controls discussed throughout this book fit together to give you total control over the Excel environment. To maximize your productivity and write robust, maintainable code, you should follow these practical rules:

  1. Always declare your variables explicitly by placing Option Explicit at the top of every module to catch spelling mistakes and data type mismatches early.
  2. Structure your code into small, modular Sub and Function procedures that perform single, well-defined tasks rather than writing long, monolithic blocks of code.
  3. Eliminate unnecessary range selections and screen refreshing by directly manipulating object properties, which dramatically accelerates your macro execution speed.
  4. Implement comprehensive error handling using On Error GoTo statements to anticipate unexpected user inputs or file states and prevent abrupt application crashes.
  5. Save your workbooks in the macro-enabled file format and organize your custom procedures into reusable add-ins that remain accessible across all your projects.
  6. Design clean UserForms with intuitive toolbox controls and descriptive naming conventions to create professional interfaces for non-technical spreadsheet users.
  7. Test your event handlers and conditional logic thoroughly across various data scenarios to ensure your automated solutions behave predictably under all conditions.

By applying these principles consistently, you turn raw data into polished, efficient applications. You now possess the foundational knowledge needed to solve complex spreadsheet challenges and customize Excel to meet your exact professional requirements.

10 Key Ideas

  1. Visual Basic for Applications acts as a powerful programming language built directly into Excel to automate routine commands and eliminate manual spreadsheet labor.
  2. You can jumpstart your programming journey by recording manual actions into reusable code and saving workbooks in macro-enabled formats.
  3. Excel organizes its entire application architecture into a hierarchical object model controlled through properties and methods.
  4. VBA divides tasks between Sub procedures that execute actions and Function procedures that perform calculations and return values.
  5. Writing robust code requires mastering variable declarations, explicit scoping rules, dynamic arrays, and efficient range references.
  6. You can direct how your code executes by using conditional If-Then statements, Select Case branches, and flexible looping structures.
  7. Automatic event handlers and strategic error-trapping mechanisms allow your macros to respond to user actions and avoid abrupt crashes.
  8. Optimizing your code execution speed and avoiding unnecessary range selections will transform sluggish macros into lightning-fast routines.
  9. You can build fully interactive custom dialog boxes using UserForms, toolbox controls, and event-handler subroutines.
  10. Expanding Excel capabilities involves writing custom user-defined functions and packaging your macros into professional add-in files.

A summary is an independent retelling, not the text of the book.

Cover of the summary of “The Last Whalers” 20 min read

The Last Whalers

Doug Bock Clark
Cover of the summary of “Confess” 21 min read

Confess

Rob Halford
Cover of the summary of “Toast” 17 min read

Toast

Nigel Slater
Cover of the summary of “Ace Voices” 24 min read

Ace Voices

Eris Young
Cover of the summary of “For Small Creatures Such as We” 17 min read
Cover of the summary of “Two Trees Make a Forest” 16 min read
Cover of the selected audiobook Choose a chapter The player is ready
0:00 0:00

Volume