Advanced Excel · Intermediate level

Intermediate level · Module 5: Automating Excel · Lesson 2 of 3

Basic VBA

Read and improve recorded code, and write simple procedures with variables and loops.

In this lesson you will

  • Read and clean up recorded VBA
  • Write a procedure that loops over sheets or rows

Key concepts

VBA editorSub procedurevariablesFor Each loop

The lesson

Open the VBA editor (Alt+F11) to see recorded code. Recorded code is long because it captures every click; removing Select and Activate lines makes it shorter and faster.

Procedures (Sub … End Sub) can use variables and loops: For Each ws In ThisWorkbook.Worksheets repeats an action on every sheet.

Add comments, use clear names and add error handling, so others can maintain the code.

Step by step

  1. Open a recorded macro in the editor.
  2. Remove unnecessary Select statements.
  3. Write a loop that exports each branch sheet to PDF.
  4. Add comments and simple error handling.

Practice activity

Complete the branch PDF export from the practical activity.

Expected result: A readable procedure that exports every branch report correctly.

Check your understanding

  1. Which shortcut opens the VBA editor?

    Show answer

    Alt+F11.

  2. Why remove Select and Activate from recorded code?

    Show answer

    They make code longer, slower and more fragile.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.