A VBA cheat sheet is a condensed reference of the most common Visual Basic for Applications commands, object hierarchies, and syntax rules used to automate tasks in Microsoft Office. It allows you to quickly find the correct property or method without browsing through full documentation.
Core Syntax and Variable Declarations
Every VBA procedure begins with a declaration that defines its scope and return type. Use Sub for a sequence of instructions that performs an action and Function for a calculation that returns a value. Declaring variables with Dim ensures that the computer allocates the correct amount of memory and prevents errors caused by typos in variable names.
Choosing the right data type prevents memory waste and logic errors. Use Integer for small whole numbers, Long for larger whole numbers, Double for decimals, and String for text. The Variant type is the default if you do not specify one, but it is slower and uses more memory. Always place Option Explicit at the very top of your module to force the declaration of all variables, which helps you spot misspelled names immediately.
| Data Type | Storage Use | Typical Use Case |
|---|---|---|
| Integer | 2 bytes | Small counters (up to 32,767) |
| Long | 4 bytes | Row counts in large sheets |
| Double | 8 bytes | Precise financial or scientific decimals |
| String | Variable | Names, addresses, or labels |
Excel Object Hierarchy and Cell Referencing
VBA views Excel as a hierarchy of objects. The Application is the top level, followed by Workbook, then Worksheet, and finally Range. To change a cell value, you typically navigate this path. If you omit the workbook or worksheet, VBA assumes you are referring to the currently active one, but specifying the exact sheet prevents your code from accidentally editing the wrong page.
There are two primary ways to reference a cell. Range("A1") uses the standard Excel address and is easy to read. Cells(row, col) uses numeric indices, such as Cells(1, 1) for A1. Use Cells when you are writing a loop, as it allows you to use a variable for the row or column number. For example, Cells(i, 1) can move down a column as the value of i increases.
To reference a dynamic range, use End(xlUp). This mimics pressing Ctrl + Up Arrow in Excel. It is the most reliable way to find the last used row in a column because it starts from the bottom of the sheet and moves up until it hits data, avoiding gaps in your dataset.
Control Flow and Logic Loops
Logic structures allow your code to make decisions or repeat actions. Use If...Then...Else for simple binary choices. If you have multiple specific conditions to check against a single variable, a Select Case block is cleaner and easier to maintain than nested If statements. It lists the variable once and then lists several possible outcomes.
Loops are used to process lists of data. A For...Next loop is best when you know exactly how many times the code should run, such as looping from row 1 to row 100. A For Each...Next loop is more efficient when dealing with a collection of objects, such as every worksheet in a workbook or every cell in a selected range. It removes the need to track a numeric counter.
Use a Do While...Loop or Do Until...Loop when the number of iterations is unknown and depends on a condition being met. For instance, you might tell VBA to keep reading rows until it encounters a blank cell. Be careful to include a way for the loop to end, or you may cause the application to freeze in an infinite loop.
Common Methods and Properties Reference
Methods are actions you perform on an object, while properties are characteristics you can get or set. To change the color of a cell, you set the Interior.Color property. To clear the contents of a range without deleting the formatting, use the .ClearContents method. To delete the entire row, use .Delete.
When working with values, distinguish between .Value and .Text. The .Value property retrieves the actual data stored in the cell, including the raw number. The .Text property retrieves exactly what is displayed on the screen, including currency symbols or date formatting. Using .Value is generally safer for calculations.
To speed up your code, disable screen updating and automatic calculations at the start of your macro. Use Application.ScreenUpdating = False. This stops Excel from redrawing the screen every time a cell changes, which can reduce the execution time of a large script from several minutes to a few seconds. Remember to set it back to True at the end of the procedure.
Error Handling and Debugging Techniques
Errors occur when VBA encounters an unexpected state, such as trying to open a file that does not exist. Use On Error Resume Next only for lines where you expect a potential error and want the code to ignore it. For more robust scripts, use On Error GoTo ErrorHandler. This sends the code to a specific label at the bottom of your procedure where you can display a friendly message to the user instead of a technical crash report.
The most effective way to find a bug is by using the F8 key. Pressing F8 allows you to step through your code one line at a time. As you do this, you can hover your mouse over any variable to see its current value. This reveals exactly where a calculation goes wrong or why a loop is skipping a row.
The Immediate Window (Ctrl + G) is a powerful tool for testing small snippets of code or printing values while the macro is running. Use the Debug.Print command to send a value to this window. This allows you to track the progress of a loop without using dozens of pop-up message boxes that interrupt the flow of the program.
Practical Worked Example: Data Cleanup
Consider a scenario where you have a list of names in Column A and need to remove all rows where the name is missing. You would first find the last row using lastRow = Cells(Rows.Count, 1).End(xlUp).Row. Because deleting rows shifts the remaining rows upward, you must loop from the bottom to the top. If you loop from the top down, you will skip the row immediately following a deleted one.
- Declare a Long variable for the row counter.
- Set the loop to run from
lastRow To 1 Step -1. - Inside the loop, use an
If Cells(i, 1).Value = "" Thenstatement. - Call
Rows(i).Deleteif the condition is true. - End the If block and the For loop.
This logic ensures that every cell is checked. A rule of thumb for VBA is to always work backwards when deleting items from a list. This maintains the integrity of the index and ensures no data is overlooked. If you are adding data, work forwards; if you are removing data, work backwards.