Free · 3 minutes · no registration Your IT profession: Backend developer? Find the profession that suits me
29 November 2026

Your first Excel VBA macro: automating repetitive tasks

Your first Excel VBA macro: automating repetitive tasks

Every week you open the same report: you make the headers bold, format the numbers, highlight large amounts in colour and adjust the column widths. It takes 15–20 minutes every time, and the steps are always the same. Excel has a built-in answer to repetitive work like this: writing a macro with Excel VBA. In this article we show, step by step, what a macro is, how to record your first one without writing any code, and then how to automate a real reporting task with simple VBA code. No programming experience is needed — being comfortable in Excel is enough.

What is VBA and what are macros for?

VBA (Visual Basic for Applications) is a programming language built into Microsoft Office applications. In Excel, a sequence of commands written in VBA is called a macro. A macro can repeat the steps you would otherwise do by hand — selecting cells, applying formatting, adding sheets, saving the file — with a single click and in a matter of seconds.

Macros are most often used for:

  • formatting reports in a consistent way;
  • pulling data from several sheets or files into one table;
  • checking data against conditions and flagging it;
  • creating a separate sheet or file for each department or region;
  • building simple forms (UserForms) for users to enter data.

In accounting, finance, sales, logistics and HR, Excel is an everyday tool, so an employee who knows VBA can cut down the routine tasks that eat up most of the team's time.

Before you start: three essential preparations

1. Enable the Developer tab

The macro tools are hidden by default. To show them, go to File → Options → Customize Ribbon and tick the Developer box in the list on the right. A new tab will appear on the ribbon, containing the Record Macro, Macros and Visual Basic buttons.

2. Save the file in .xlsm format

A regular .xlsx file cannot store macros. Use Save As to save a workbook with macros as an Excel Macro-Enabled Workbook (.xlsm). Otherwise Excel will warn you, and if you save the file as .xlsx anyway, the code you wrote will be lost.

3. Understand macro security

Because a macro can perform a wide range of actions on your computer, macros can also be used in malicious files. That is why Excel opens macros disabled by default and shows a warning bar at the top, and it may block macros entirely in files downloaded from the internet. The rule is simple: only enable macros in files whose source you trust. The security settings are under File → Options → Trust Center; switching them to “enable all macros” is not recommended.

Your first macro: a code-free start with the Macro Recorder

The easiest way to learn VBA is to watch Excel write the code for you. The Macro Recorder follows your actions and turns them into VBA code.

  1. Click Developer → Record Macro.
  2. Give the macro a name (no spaces, for example HeaderFormat) and, if you like, assign a keyboard shortcut.
  3. Leave This Workbook selected in the “Store macro in” field.
  4. Work as you normally would: select the header row, make it bold, add a fill colour and autofit the column widths.
  5. Click Stop Recording.

Now, if you go to another sheet, pick the macro in the Developer → Macros window and click Run, the same steps will be repeated automatically.

The Recorder is a good starting point, but it has limitations: it writes every click and every selection into the code, uses fixed cell addresses (for example, always A1:D20) and cannot build conditions or loops. If tomorrow your table has 350 rows instead of 20, the recorded macro will only do part of the job. That is why the next step is writing the code yourself.

Getting to know the VBA editor

The Alt + F11 shortcut opens the VBA editor (Visual Basic Editor). At first, you will need three parts of it:

  • Project Explorer shows open workbooks, their sheets and modules as a tree;
  • Module is where you write code; you add a new module via Insert → Module (the code written by the Recorder usually ends up in Module1 too);
  • Immediate Window (Ctrl + G) is for testing short commands and viewing results with Debug.Print.

F5 runs the code, while F8 steps through it line by line — the most useful habit for understanding what a macro does and tracking down bugs.

A practical example: automating a sales report with Excel VBA

Suppose a sheet called Sales has the date, manager, product and amount in columns A–D, and the number of rows changes every week. The goal is to format the header, apply a number format to the amounts and tidy up the columns.

Sub FormatReport()
 Dim ws As Worksheet
 Dim lastRow As Long

 Set ws = ThisWorkbook.Worksheets("Sales")
 lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

 With ws.Range("A1:D1")
 .Font.Bold = True
 .Font.Color = RGB(255, 255, 255)
 .Interior.Color = RGB(31, 111, 85)
 End With

 ws.Range("D2:D" & lastRow).NumberFormat = "#,##0.00"
 ws.Columns("A:D").AutoFit

 MsgBox "Rows formatted: " & lastRow - 1
End Sub

Let's go through the code piece by piece:

  • Dim declares the variables: ws holds the sheet, and lastRow holds the number of the last filled row.
  • The End(xlUp) line works out the size of the table by itself: it starts at the very bottom of column A and moves up to the first filled cell. As a result, the macro works correctly whether the table has 20 rows or 5,000.
  • The With ... End With block lets you apply several commands to the same object without repeating its name.
  • MsgBox shows a short notification when the work is done.

A small but practical tip: the VBA editor may not display some letters of the Azerbaijani alphabet (such as ə, ı and ş) correctly in text inside the code. So it is safer to stick to Latin letters in variable names and messages.

Loops and conditions: highlighting large sales

The real power of macros shows up in conditions and loops. The code below checks every cell in the amount column and highlights sales greater than or equal to 1000 with a light green fill:

Sub HighlightLargeSales()
 Dim ws As Worksheet
 Dim cell As Range
 Dim lastRow As Long

 Set ws = ThisWorkbook.Worksheets("Sales")
 lastRow = ws.Cells(ws.Rows.Count, "D").End(xlUp).Row

 For Each cell In ws.Range("D2:D" & lastRow)
 If IsNumeric(cell.Value) And Not IsEmpty(cell.Value) Then
 If cell.Value >= 1000 Then
 cell.Interior.Color = RGB(230, 241, 236)
 End If
 End If
 Next cell
End Sub

The For Each loop goes through the cells in the range one by one, while the nested If blocks first check whether the cell contains a number and then whether the amount exceeds the threshold. Splitting the check into two steps is deliberate: in VBA, the And operator evaluates both sides of the condition, so if a cell contains text, comparing it directly could cause an error.

Preparing for errors: On Error

If the sheet has been renamed, the macro above will stop with a “Subscript out of range” error. To show the user a clear message instead of a confusing dialog box, you use error handling:

Sub SafeRun()
 On Error GoTo ErrorHandler
 FormatReport
 HighlightLargeSales
 Exit Sub
ErrorHandler:
 MsgBox "An error occurred: " & Err.Description
End Sub

This macro calls both procedures in turn and, if something goes wrong, shows a description of the error. As a final step, you can link the macro to a button placed on the sheet (Developer → Insert → Button) — then even colleagues who don't know VBA can prepare the report with a single click.

Common beginner mistakes

  • Working without a backup. Changes made by a macro cannot be undone with Ctrl + Z. Always test a new macro on a copy of the file.
  • Code full of Select and Activate. Lines left over from the Recorder, such as Range("A1").Select, slow the code down and make it fragile. Work with objects directly: ws.Range("A1").Font.Bold = True.
  • Fixed ranges. Addresses like A2:D100 cause problems as the table grows. Find the last row in code.
  • Not declaring variables. Put Option Explicit at the very top of the module: VBA will then flag every undeclared variable as an error, and you will catch typos straight away.
  • Saving the file as .xlsx. The code is lost — always choose .xlsm for files with macros.

Is VBA still worth learning?

In recent years, other automation tools have appeared in Excel: Power Query for importing and cleaning data, Office Scripts for Excel on the web, and Python for analytical work. Each has its place, and Power Query, for example, is often more convenient for cleaning data. Even so, VBA is still widely used in desktop Excel, many companies have macro-enabled files that have been running for years, and there is still demand for specialists who can maintain them. VBA's main advantage is that it can control almost every element of Excel and can also work with other Office applications such as Word and Outlook. Keep in mind that VBA macros do not run in Excel for the web — they are for desktop Excel.

Conclusion

You don't need to be a programmer to write macros. Start with the Macro Recorder and look at the code it produces, then make it flexible with variables, the With block, If conditions and the For Each loop — this path lets you turn weeks of repetitive manual work into a single button. Your own daily work is the best practice: pick the repetitive step that takes up the most time and try to automate it with a small macro.

If you want to learn working with cells, sheets and workbooks, conditions and loops, arrays, UserForms, event procedures and error handling in a structured way through a final project, take a look at Orient Academy's VBA Excel course.

Course programs

IT Service Management

Office Software Courses

Python courses

1Z0-830 – Java SE 21 Developer Professional (Java 21)

Help Desk courses

Training program courses for children

Network Administration Courses

QA courses

Don't know where to start?

Apply

Complete your application for the chosen course and let us share our knowledge with you.

+994
+ Add a message

Your data is used only to contact you.

Contact us directly (+994 10) 234 65 56