TechBuzzPro

Sample VBA Code: A Practical Excel Macro Example

· 6 min read · Apps & Browsers

In this article
  1. What VBA is and where the code runs
  2. How to add and run the sample
  3. Understanding the main parts
  4. Adapt the example to your workbook
  5. Common problems and safe use
  6. Frequently Asked Questions

Here is a practical VBA sample for Microsoft Excel for Microsoft 365 on Windows: it reads a list of names and values, totals the values, and writes a summary to a new worksheet. Before running any macro, save a copy of your workbook: VBA actions generally cannot be reversed with Ctrl+Z.

Option Explicit

Sub CreateSalesSummary()
    Dim sourceSheet As Worksheet
    Dim reportSheet As Worksheet
    Dim lastRow As Long
    Dim totalSales As Double
    Dim reportName As String

    ' Use the active sheet as the source data sheet.
    Set sourceSheet = ActiveSheet
    reportName = "Summary"

    ' Find the last used row in column A.
    lastRow = sourceSheet.Cells(sourceSheet.Rows.Count, "A").End(xlUp).Row

    If lastRow < 2 Then
        MsgBox "Add a header in row 1 and data below it first.", vbExclamation
        Exit Sub
    End If

    ' Add the values in column B, excluding the header.
    totalSales = Application.WorksheetFunction.Sum( _
        sourceSheet.Range("B2:B" & lastRow))

    ' Reuse the Summary sheet if it exists; otherwise create it.
    On Error Resume Next
    Set reportSheet = ThisWorkbook.Worksheets(reportName)
    On Error GoTo 0

    If reportSheet Is Nothing Then
        Set reportSheet = ThisWorkbook.Worksheets.Add
        reportSheet.Name = reportName
    Else
        reportSheet.Cells.Clear
    End If

    ' Write a simple report.
    reportSheet.Range("A1").Value = "Sales summary"
    reportSheet.Range("A2").Value = "Total"
    reportSheet.Range("B2").Value = totalSales
    reportSheet.Range("A1:B2").EntireColumn.AutoFit

    MsgBox "Summary created. Total: " & Format(totalSales, "0.00"), vbInformation
End Sub

This example expects a header in row 1, names or descriptions in column A, and numeric amounts in column B. It is a starting point rather than a universal macro: change the sheet selection, columns, and report output to match your workbook.

What VBA is and where the code runs

VBA, or Visual Basic for Applications, is the programming language built into desktop versions of Microsoft Office. In Excel, VBA can automate repetitive work, manipulate cells and worksheets, and respond to events such as opening a workbook or changing a cell. A procedure beginning with Sub and ending with End Sub is a macro that you can run directly.

Excel for the web can open and edit many macro-enabled workbooks, but it cannot create, run, or edit VBA macros. Use Excel desktop for Windows for the instructions here. Excel for Mac supports VBA, although some Windows-specific features, automation interfaces, and keyboard shortcuts may not be available or may behave differently.

How to add and run the sample

  1. Save a backup copy of the workbook. If you want to keep VBA in the working file, use Excel Macro-Enabled Workbook format (.xlsm); a standard .xlsx file does not preserve VBA code.
  2. Open the Visual Basic Editor with Alt+F11 on Windows. On Mac, the commonly used shortcut is Option+F11; depending on the keyboard, you may need Fn as well. You can also open the editor from the Developer tab.
  3. In the editor, choose Insert > Module, then paste the complete code into the module window. If the Developer tab is hidden in Windows Excel, enable it through File > Options > Customize Ribbon.
  4. Return to Excel, select the sheet containing the data, and run the macro from Developer > Macros. Select CreateSalesSummary, then choose Run. In the Visual Basic Editor, you can also place the cursor inside the procedure and press F5.

The macro writes to a worksheet named Summary. If that sheet already exists, its cells are cleared before the new total is written. Check that it does not contain information you need to keep; the backup is important for that reason as well as because Ctrl+Z does not undo a macro.

Understanding the main parts

  • Option Explicit requires variables to be declared. This helps catch misspelled variable names instead of silently treating them as new variables.
  • The Dim lines declare variables and their types. A Worksheet variable refers to a worksheet, Long holds the row number, and Double stores a numeric total that can include decimals.
  • Cells(Rows.Count, "A").End(xlUp).Row starts at the bottom of column A and moves up to its last non-empty cell. This is a common way to find the data boundary when column A is filled for every record.
  • WorksheetFunction.Sum delegates addition to Excel’s SUM function. The code builds a range from B2 to the last data row, leaving out the header.
  • The error-handling lines briefly suppress an error while checking whether the Summary sheet exists, then turn normal error handling back on. The code creates the sheet only if it was not found.

Adapt the example to your workbook

If the amounts are in column D, change both references to column B: the range used by WorksheetFunction.Sum and the code that determines the last row if column D is the consistently populated field. If your data is on a sheet with a known name, you can replace Set sourceSheet = ActiveSheet with Set sourceSheet = ThisWorkbook.Worksheets("Data"). The name inside quotation marks must match the worksheet tab exactly.

For more dependable reporting, consider converting the source range into an Excel table and referring to that table, particularly if rows are added regularly. The sample’s last-row method assumes there are no gaps in the chosen column that make the bottommost record an unreliable boundary. It also assumes column B contains numeric values; text entries are not added by SUM.

Common problems and safe use

  • The macro does not appear in the list: confirm that the code is in a standard module, that the procedure is a public Sub without arguments, and that the workbook is saved as .xlsm.
  • Excel blocks macros: only enable macros in files you trust. A macro can change or delete workbook data and may perform other actions. Do not lower security settings to run code from an unknown source; follow your organization’s security policy.
  • A sheet-name error occurs: check for spelling, spaces, and punctuation in the tab name. If a sheet named Summary already exists, the example reuses it and clears its cells.
  • The total is wrong or zero: verify that the values are in column B, start in row 2, and are stored as numbers rather than text. Confirm that column A contains the records used to determine the last row.
  • Ctrl+Z does not restore the workbook: that is expected for VBA macros. Close without saving if you need to discard the changes, or restore the backup you made first.

Frequently Asked Questions

Where do I paste VBA code in Excel?
Open the Visual Basic Editor, choose Insert > Module, and paste the code into the module window. A standard module is suitable for a macro you run from Developer > Macros.

How do I run a VBA macro?
In desktop Excel, use Developer > Macros, select the macro, and choose Run. You can also run a procedure from the Visual Basic Editor with the cursor inside it and press F5.

Can I run VBA in Excel for the web?
No. Excel for the web does not run VBA macros. Open the workbook in desktop Excel to run or edit its VBA code.

Why does Excel remove my macro?
If you save a workbook with VBA as .xlsx, Excel warns that the format cannot store macros. Choose Excel Macro-Enabled Workbook (.xlsm) to retain the VBA project.

Can I undo a VBA macro with Ctrl+Z?
Usually not. Running VBA clears Excel’s normal undo history, so save a separate copy before running a macro that changes workbook contents.