Excel Agility: Macro Basics Part 4
Notice: No webinar is currently available in this series.
This webinar is not currently available, new dates coming soon.
Frequently Asked Questions
A user-defined function (UDF) is a custom formula you create in VBA that can be used directly in worksheet cells, just like built-in functions such as SUM or VLOOKUP. UDFs are defined using the Function keyword in a VBA module: Function MyFunction(arg1 As Double) As Double ... End Function. Once created, the function appears in Excel's formula autocomplete and can be called with =MyFunction(A1). UDFs are ideal when built-in functions cannot perform the calculation you need—such as extracting specific text patterns, applying business-specific formulas, or combining multiple operations into a single reusable function. Unlike Sub procedures, UDFs cannot modify cells, format worksheets, or run macros—they can only calculate and return a value. UDFs stored in the Personal Macro Workbook are available across all Excel files. For accounting and finance professionals with specialized calculation needs, UDFs bridge the gap between Excel's built-in capabilities and custom business logic without requiring complex formula chains in every cell.
MsgBox and InputBox are VBA functions that display dialog boxes to communicate with users during macro execution. MsgBox displays a message with customizable buttons—OK, Yes/No, Cancel, etc.—and returns the button the user clicked, enabling conditional branching. For example: If MsgBox("Proceed?", vbYesNo) = vbNo Then Exit Sub cancels the macro if the user clicks No. You can customize the title, icon (information, warning, critical), and button layout. InputBox prompts the user to type a value and returns it as a string, useful for letting users specify parameters like a date range, report name, or output path at runtime. The Application.InputBox version adds type validation—specifying Type:=1 restricts input to numbers, Type:=8 allows the user to select a cell range directly. These dialog tools transform rigid macros into flexible, interactive tools that adapt to user input at runtime, making them significantly more practical for daily use in professional Excel workflows.
Error handling in VBA prevents macros from crashing ungracefully when unexpected conditions occur—such as a file not being found, a sheet that was renamed, or a cell containing text where a number was expected. The primary error handling statement is On Error GoTo LabelName, which redirects execution to a labeled section when a runtime error occurs. In that section, you can display a user-friendly message using MsgBox Err.Description and then exit cleanly. On Error Resume Next instructs VBA to silently skip the line that caused the error and continue—useful when an error is expected and non-critical, but dangerous if overused as it can hide genuine problems. On Error GoTo 0 resets error handling to the default (stop and show error). Best practice is to wrap critical operations—file opens, sheet references, external data connections—in specific error handlers. Proper error handling is the difference between professional-grade macros that fail gracefully and fragile scripts that confuse users with cryptic VBA error dialogs during routine operations.
The VBA editor provides several built-in debugging tools to help identify and fix macro errors. Setting a breakpoint (click in the grey margin next to a code line, or press F9) pauses execution at that point, allowing you to inspect variable values by hovering over them or using the Immediate Window. The Immediate Window (Ctrl+G) lets you print variable values mid-execution with Debug.Print statements or execute VBA commands interactively. Step Into (F8) executes code one line at a time, making it easy to track exactly where unexpected behavior occurs. The Watch Window allows you to monitor specific variable values continuously as code runs. The Locals Window shows all current variable values in the active procedure. For logic errors rather than syntax errors, adding Debug.Print statements to log intermediate values to the Immediate Window is often the fastest diagnostic approach. Systematic debugging skills separate proficient VBA developers from beginners and are essential for maintaining reliable Excel automation in production environments.
Several VBA optimization techniques can dramatically reduce macro execution time on large datasets. The most impactful is turning off screen updating at the start of the macro with Application.ScreenUpdating = False and restoring it at the end—this prevents Excel from redrawing the screen after every change, often cutting runtime by 50-90% for visual operations. Similarly, setting Application.Calculation = xlCalculationManual prevents recalculation after each cell change; restore it to xlCalculationAutomatic at the end and call Calculate once. Avoid selecting cells before acting on them—Recorder-generated code like Range("A1").Select followed by Selection.Value = X is much slower than Range("A1").Value = X directly. Reading and writing entire arrays at once—assigning a range to a Variant array, processing in memory, then writing back—is orders of magnitude faster than looping through individual cells. Disabling events with Application.EnableEvents = False prevents event procedures from firing during automated operations. These optimizations are essential for macros processing thousands of rows in professional reporting workflows.