VBA course · Lesson 33 of 33

Final project: build a PDF invoice generator in VBA

Put the course together: turn order lines into one numbered invoice per customer from a template, add VAT, save each as PDF and keep a log.

Advanced 35 min read

This final lesson is a complete project that uses almost everything from the course. You will build a small but realistic tool: a workbook where order lines are typed on one sheet, and a single button creates one invoice per customer from a formatted template, numbers it, calculates VAT, saves it as a PDF in a folder and writes a log. Orders that have been invoiced are marked, so running the macro again only picks up new orders.

Build it step by step rather than pasting the whole listing at once. Every part links back to the lesson where the technique was explained, so you can revisit anything that feels unfamiliar.

What the tool does

  1. Reads settings (next invoice number, VAT rate, output folder) from a Settings sheet.
  2. Reads the Customers sheet into a dictionary for fast lookups.
  3. Reads all Orders that do not yet have an invoice number and groups them by customer.
  4. For each customer: copies the hidden Template sheet, fills in the header, the lines and the totals, exports it as a PDF and marks the order lines as invoiced.
  5. Writes one row per invoice (or per problem) to a Log sheet.
  6. Runs with screen updating, events and calculation switched off, and always switches them back on, even after an error.

The workbook layout

Five sheets are involved. The sample-data macro further down creates all of them for you, so you can start from an empty workbook.

ABCDEF
1DateCustomerIDProductQtyUnit priceInvoiced
22026-11-03C001Desk lamp432.5
32026-11-03C002Office chair2149
42026-11-05C001Monitor arm259
52026-11-06C003Paper A4 box1024.9
62026-11-09C002Whiteboard189
72026-11-12C001USB-C dock1129
82026-11-13C999Stapler37.5

Orders sheet before running (column F is empty for new orders)

ABC
1CustomerIDNameAddress
2C001Acme Ltd12 Harbour Road, Dublin
3C002Brightway4 Market Street, Leeds
4C003Coastline Foods88 Quay Lane, Cork

Customers sheet

The Settings sheet holds the next invoice number in B1, the VAT rate in B2 (0.2 for 20%) and the name of the output folder in B3 (Invoices, created next to the workbook). The Template sheet is the invoice layout: title in B2, invoice number in F3, date in F4, customer name and address in B6:B7, item headers in row 10, up to 20 item rows from row 11 to row 30, and net, VAT and total in E32:E34. The Log sheet starts with just a header row.

Customer C999 on the last order line does not exist. That is deliberate: a good tool must cope with bad data, and you will see how it is reported.

Step 1: set up the sample workbook

Insert a module, rename it modSetup (Properties window, F4) and add this code. It is a convenience: run it once in a new workbook to create the sheets with sample data and a simple invoice template. It also demonstrates writing whole rows with Array (Range and Cells: working with cells in VBA) and formatting via With blocks.

VBA
Option Explicit

Public Sub SetUpSampleWorkbook()
    Dim ws As Worksheet

    ' --- Customers ---
    Set ws = GetOrAddSheet("Customers")
    ws.Range("A1:C1").Value = Array("CustomerID", "Name", "Address")
    ws.Range("A2:C2").Value = Array("C001", "Acme Ltd", "12 Harbour Road, Dublin")
    ws.Range("A3:C3").Value = Array("C002", "Brightway", "4 Market Street, Leeds")
    ws.Range("A4:C4").Value = Array("C003", "Coastline Foods", "88 Quay Lane, Cork")
    ws.Columns("A:C").AutoFit

    ' --- Orders ---
    Set ws = GetOrAddSheet("Orders")
    ws.Range("A1:F1").Value = Array("Date", "CustomerID", "Product", "Qty", "Unit price", "Invoiced")
    ws.Range("A2:E2").Value = Array(DateSerial(2026, 11, 3), "C001", "Desk lamp", 4, 32.5)
    ws.Range("A3:E3").Value = Array(DateSerial(2026, 11, 3), "C002", "Office chair", 2, 149)
    ws.Range("A4:E4").Value = Array(DateSerial(2026, 11, 5), "C001", "Monitor arm", 2, 59)
    ws.Range("A5:E5").Value = Array(DateSerial(2026, 11, 6), "C003", "Paper A4 box", 10, 24.9)
    ws.Range("A6:E6").Value = Array(DateSerial(2026, 11, 9), "C002", "Whiteboard", 1, 89)
    ws.Range("A7:E7").Value = Array(DateSerial(2026, 11, 12), "C001", "USB-C dock", 1, 129)
    ws.Range("A8:E8").Value = Array(DateSerial(2026, 11, 13), "C999", "Stapler", 3, 7.5)
    ws.Range("A2:A8").NumberFormat = "yyyy-mm-dd"
    ws.Columns("A:F").AutoFit

    ' --- Settings ---
    Set ws = GetOrAddSheet("Settings")
    ws.Range("A1:B1").Value = Array("Next invoice number", 1)
    ws.Range("A2:B2").Value = Array("VAT rate", 0.2)
    ws.Range("A3:B3").Value = Array("PDF folder (next to this file)", "Invoices")
    ws.Range("B2").NumberFormat = "0%"
    ws.Columns("A:B").AutoFit

    ' --- Log ---
    Set ws = GetOrAddSheet("Log")
    ws.Range("A1:F1").Value = Array("Time", "Invoice", "Customer", "Net", "VAT", "File or note")
    ws.Range("A1:F1").Font.Bold = True

    ' --- Template ---
    Set ws = GetOrAddSheet("Template")
    With ws
        .Range("B2").Value = "INVOICE"
        .Range("B2").Font.Size = 20
        .Range("B2").Font.Bold = True
        .Range("E3").Value = "Invoice no."
        .Range("E4").Value = "Date"
        .Range("F4").NumberFormat = "d mmm yyyy"
        .Range("B5").Value = "Bill to:"
        .Range("B10:E10").Value = Array("Product", "Qty", "Unit price", "Amount")
        .Range("B10:E10").Font.Bold = True
        .Range("B10:E10").Interior.Color = RGB(221, 235, 247)
        .Range("D11:E34").NumberFormat = "#,##0.00"
        .Range("D32").Value = "Net"
        .Range("D33").Value = "VAT"
        .Range("D34").Value = "Total"
        .Range("D34:E34").Font.Bold = True
        .Columns("B").ColumnWidth = 30
        .Columns("C:F").ColumnWidth = 13
        .PageSetup.PrintArea = "$B$2:$F$34"
        .Visible = xlSheetHidden          ' users never edit the template by accident
    End With

    MsgBox "Sample workbook ready. Save it as .xlsm, then run CreateInvoices.", vbInformation
End Sub

' Returns the sheet with this name, cleared; creates it if it does not exist
Private Function GetOrAddSheet(ByVal sheetName As String) As Worksheet
    Dim ws As Worksheet
    On Error Resume Next
    Set ws = ThisWorkbook.Worksheets(sheetName)
    On Error GoTo 0
    If ws Is Nothing Then
        Set ws = ThisWorkbook.Worksheets.Add( _
            After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))
        ws.Name = sheetName
    Else
        ws.Cells.Clear
    End If
    Set GetOrAddSheet = ws
End Function
modSetup: create the sheets, sample data and the invoice template

GetOrAddSheet shows a pattern you will reuse often: try to get an object, swallow only that one possible error, then check the result with Is Nothing (Error handling and debugging in VBA, Workbooks and worksheets in VBA). Hiding the template with xlSheetHidden keeps it out of the way while still letting code copy it.

Save the workbook as Excel Macro-Enabled Workbook (*.xlsm) before going on (What is VBA? Macros, when to use them and macro security). The invoice macro needs a saved workbook, because the PDF folder is created next to it.

Step 2: the invoice generator

Insert a second module, name it modInvoices, and add the main code. Read the explanation after the listing; each numbered comment in the code matches a section below.

VBA
Option Explicit

' Layout of the Template sheet and the Orders sheet
Private Const FIRST_LINE_ROW As Long = 11    ' first item row on the template
Private Const MAX_LINES As Long = 20         ' item rows 11 to 30
Private Const COL_INVOICED As Long = 6       ' column F of Orders

Public Sub CreateInvoices()
    Dim wsOrders As Worksheet, wsCust As Worksheet, wsTpl As Worksheet
    Dim wsSet As Worksheet, wsLog As Worksheet, wsInv As Worksheet
    Dim orders As Variant, custData As Variant
    Dim customers As Object, groups As Object
    Dim lines As Collection
    Dim custId As Variant, rowIdx As Variant
    Dim r As Long, i As Long, lastRow As Long, cRow As Long
    Dim nextNo As Long, vatRate As Double
    Dim invNo As String, outFolder As String, pdfPath As String
    Dim netTotal As Currency, vatAmount As Currency
    Dim items() As Variant
    Dim made As Long, skipped As Long
    Dim calcMode As XlCalculation
    Dim inProgress As Boolean
    Dim errMsg As String

    If ThisWorkbook.Path = "" Then
        MsgBox "Please save this workbook first.", vbExclamation
        Exit Sub
    End If

    Set wsOrders = ThisWorkbook.Worksheets("Orders")
    Set wsCust = ThisWorkbook.Worksheets("Customers")
    Set wsTpl = ThisWorkbook.Worksheets("Template")
    Set wsSet = ThisWorkbook.Worksheets("Settings")
    Set wsLog = ThisWorkbook.Worksheets("Log")

    ' ---- 1. Settings ----
    nextNo = wsSet.Range("B1").Value
    vatRate = wsSet.Range("B2").Value
    outFolder = ThisWorkbook.Path & Application.PathSeparator & wsSet.Range("B3").Value
    If Dir(outFolder, vbDirectory) = "" Then MkDir outFolder
    outFolder = outFolder & Application.PathSeparator

    ' ---- 2. Customers: ID -> row number in custData ----
    lastRow = wsCust.Cells(wsCust.Rows.Count, "A").End(xlUp).Row
    custData = wsCust.Range("A2:C" & lastRow).Value
    Set customers = CreateObject("Scripting.Dictionary")
    customers.CompareMode = vbTextCompare
    For r = 1 To UBound(custData, 1)
        customers(CStr(custData(r, 1))) = r
    Next r

    ' ---- 3. Group the open order lines by customer ----
    lastRow = wsOrders.Cells(wsOrders.Rows.Count, "A").End(xlUp).Row
    If lastRow < 2 Then
        MsgBox "There are no orders.", vbInformation
        Exit Sub
    End If
    orders = wsOrders.Range("A2:F" & lastRow).Value
    Set groups = CreateObject("Scripting.Dictionary")
    groups.CompareMode = vbTextCompare
    For r = 1 To UBound(orders, 1)
        If orders(r, COL_INVOICED) = "" Then          ' not invoiced yet
            custId = CStr(orders(r, 2))
            If Not groups.Exists(custId) Then groups.Add custId, New Collection
            Set lines = groups(custId)
            lines.Add r                                ' remember the row in the array
        End If
    Next r
    If groups.Count = 0 Then
        MsgBox "All orders are already invoiced.", vbInformation
        Exit Sub
    End If

    ' ---- 4. Speed settings, with a safe way back ----
    calcMode = Application.Calculation
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual
    On Error GoTo Fail

    ' ---- 5. One invoice per customer ----
    For Each custId In groups.Keys
        Set lines = groups(custId)
        If Not customers.Exists(custId) Then
            WriteLog wsLog, "", CStr(custId), 0, 0, "Skipped: customer ID not on the Customers sheet"
            skipped = skipped + 1
        ElseIf lines.Count > MAX_LINES Then
            WriteLog wsLog, "", CStr(custId), 0, 0, "Skipped: more than " & MAX_LINES & " lines"
            skipped = skipped + 1
        Else
            invNo = "INV-" & Year(Date) & "-" & Format(nextNo, "0000")
            cRow = customers(custId)

            ' 5a. Copy the template to a new sheet at the end
            wsTpl.Copy After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count)
            Set wsInv = ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count)
            inProgress = True
            wsInv.Visible = xlSheetVisible
            wsInv.Name = invNo

            ' 5b. Header
            wsInv.Range("F3").Value = invNo
            wsInv.Range("F4").Value = Date
            wsInv.Range("B6").Value = custData(cRow, 2)
            wsInv.Range("B7").Value = custData(cRow, 3)

            ' 5c. Item lines, built in an array and written in one go
            ReDim items(1 To lines.Count, 1 To 4)
            netTotal = 0
            i = 0
            For Each rowIdx In lines
                i = i + 1
                items(i, 1) = orders(rowIdx, 3)                            ' product
                items(i, 2) = orders(rowIdx, 4)                            ' qty
                items(i, 3) = orders(rowIdx, 5)                            ' unit price
                items(i, 4) = Round(orders(rowIdx, 4) * orders(rowIdx, 5), 2)
                netTotal = netTotal + items(i, 4)
            Next rowIdx
            wsInv.Range("B" & FIRST_LINE_ROW).Resize(lines.Count, 4).Value = items

            ' 5d. Totals
            vatAmount = Round(netTotal * vatRate, 2)
            wsInv.Range("E32").Value = netTotal
            wsInv.Range("E33").Value = vatAmount
            wsInv.Range("E34").Value = netTotal + vatAmount

            ' 5e. PDF
            pdfPath = outFolder & invNo & " " & CleanFileName(CStr(custData(cRow, 2))) & ".pdf"
            wsInv.ExportAsFixedFormat Type:=xlTypePDF, Filename:=pdfPath

            ' 5f. Mark the order lines, log, and move the counter on
            For Each rowIdx In lines
                wsOrders.Cells(rowIdx + 1, COL_INVOICED).Value = invNo     ' +1: header row
            Next rowIdx
            WriteLog wsLog, invNo, CStr(custData(cRow, 2)), netTotal, vatAmount, pdfPath
            nextNo = nextNo + 1
            wsSet.Range("B1").Value = nextNo                               ' save at once
            inProgress = False
            made = made + 1
        End If
    Next custId

CleanExit:
    ' ---- 6. Always restore the settings ----
    Application.Calculation = calcMode
    Application.EnableEvents = True
    Application.ScreenUpdating = True
    If errMsg = "" Then
        MsgBox made & " invoice(s) created, " & skipped & " skipped." & vbCrLf & _
            "PDFs are in " & outFolder, vbInformation
    Else
        MsgBox "Stopped: " & errMsg & vbCrLf & made & " invoice(s) were created before the error.", vbCritical
    End If
    Exit Sub

Fail:
    errMsg = Err.Description
    ' Remove a half-finished invoice sheet, so the number can be reused
    If inProgress Then
        Application.DisplayAlerts = False
        wsInv.Delete
        Application.DisplayAlerts = True
    End If
    WriteLog wsLog, invNo, "", 0, 0, "ERROR: " & errMsg
    Resume CleanExit
End Sub

' Adds one row to the Log sheet
Private Sub WriteLog(ByVal wsLog As Worksheet, ByVal invNo As String, ByVal customer As String, _
        ByVal net As Currency, ByVal vat As Currency, ByVal note As String)
    Dim r As Long
    r = wsLog.Cells(wsLog.Rows.Count, "A").End(xlUp).Row + 1
    wsLog.Cells(r, 1).Resize(1, 6).Value = Array(Now, invNo, customer, net, vat, note)
End Sub

' Replaces characters that are not allowed in file names
Private Function CleanFileName(ByVal text As String) As String
    Dim badChar As Variant
    For Each badChar In Array("\", "/", ":", "*", "?", """", "<", ">", "|")
        text = Replace(text, badChar, "-")
    Next badChar
    CleanFileName = Trim$(text)
End Function
modInvoices: the complete invoice generator

How it works, section by section

Before the sections: declarations and guard clauses

All variables are declared at the top, so Option Explicit can catch typos (Variables and data types: Dim, Option Explicit and scope). The first If is a guard clause: if the workbook was never saved, ThisWorkbook.Path is empty and there is nowhere to put the PDFs, so the macro stops politely before doing anything. Then each sheet gets its own variable, which keeps the rest of the code short and readable.

1. Settings

The next invoice number, VAT rate and folder name come from the Settings sheet rather than from constants in the code (VBA best practices: clean code, sharing and security). An accountant can change the VAT rate without opening the VBA editor. The output folder is built with Application.PathSeparator and created with MkDir if it is missing (Files and folders: open, save, loop through files and write text files).

2. Customers in a dictionary

The customer table is read into an array in one go (Arrays in VBA: static, dynamic and fast range processing), and a dictionary maps each customer ID to its row in that array (Collections and dictionaries in VBA). Later, customers(custId) finds a customer instantly instead of searching the sheet for every invoice. vbTextCompare makes c001 and C001 the same key, forgiving typing differences.

3. Grouping the orders

The orders are also read into an array. For every line without an invoice number, the macro looks up the customer's group in a second dictionary: if the customer is new, it adds a new, empty Collection; then it adds the line's row number to that collection. After this loop, groups holds something like C001 → rows 1, 3, 6, C002 → rows 2, 5. Grouping first and writing later is a common shape for reporting macros.

Note Set lines = groups(custId) followed by lines.Add r: taking the collection out into a typed variable first is clearer and avoids quirks with late-bound dictionaries.

4. Speed settings

Screen updating, events and automatic calculation are switched off for speed (Make your macros fast: speed optimization in VBA). The user's calculation mode is saved first, so it can be restored exactly. From the On Error GoTo Fail line onwards, any error jumps to the handler instead of stopping the macro with the settings still switched off.

5. One invoice per customer

The loop goes through the dictionary's keys. Two If branches deal with bad data before any sheet is created (Making decisions: If, ElseIf and Select Case): an unknown customer ID, or more lines than the template has room for. Both are logged rather than silently ignored; a tool that skips data without saying so is worse than one that stops.

For a good customer:

  • 5a. wsTpl.Copy After:=... places a copy of the template after the last sheet. Copy does not return the new sheet, so the code picks it up as the last worksheet. Because the template is hidden, the copy is hidden too, so it is made visible. The sheet is named after the invoice number, which is unique.
  • 5b. The header cells are filled from the customer array.
  • 5c. The item lines go into a 2-D array of the right size (ReDim items(1 To lines.Count, 1 To 4)) and are written with one Resize(...).Value = items. Each line amount is rounded to cents before it is added to the total, so the total always equals the sum of the printed lines.
  • 5d. VAT is rounded once, on the net total, as most invoicing rules require. The values are written as numbers, and the template's number format shows two decimals.
  • 5e. ExportAsFixedFormat saves the sheet as a PDF using the template's print area. The customer's name passes through CleanFileName, because characters such as / or : in a company name would make the file name invalid.
  • 5f. Only after the PDF exists are the order lines marked with the invoice number (rowIdx + 1 because array row 1 is sheet row 2), the log written and the counter increased and saved. Saving the counter immediately means that even if invoice number five fails, invoices one to four keep their numbers and the next run continues at five.

6. Clean exit and the error handler

Both the normal path and the error path end at CleanExit, which restores the three settings. In Fail, the error message is stored first (later statements could reset Err), a half-finished invoice sheet is deleted so its number can be reused, the error is logged, and Resume CleanExit leaves the error state and jumps to the clean-up. This single exit pattern is the one recommended in Error handling and debugging in VBA.

The result

Run CreateInvoices with the sample data and you get three invoice sheets, three PDFs in the Invoices folder, and a message saying "3 invoice(s) created, 1 skipped." The figures, with 20% VAT:

InvoiceCustomerLinesNetVATTotal
INV-2026-0001Acme Ltd3377.0075.40452.40
INV-2026-0002Brightway2387.0077.40464.40
INV-2026-0003Coastline Foods1249.0049.80298.80
BCDE
10ProductQtyUnit priceAmount
11Desk lamp432.5130
12Monitor arm259118
13USB-C dock1129129

The item area of sheet INV-2026-0001 (rows 11 to 13 filled, totals in E32:E34)

ABCDEF
1DateCustomerIDProductQtyUnit priceInvoiced
22026-11-03C001Desk lamp432.5INV-2026-0001
32026-11-03C002Office chair2149INV-2026-0002
42026-11-05C001Monitor arm259INV-2026-0001
52026-11-06C003Paper A4 box1024.9INV-2026-0003
62026-11-09C002Whiteboard189INV-2026-0002
72026-11-12C001USB-C dock1129INV-2026-0001
82026-11-13C999Stapler37.5

Orders sheet after running: invoiced lines are marked, the unknown customer stays open

Add customer C999 to the Customers sheet and run the macro again: only the stapler order is picked up, and it becomes INV-2026-0004. Run it a third time and you get "All orders are already invoiced."

Step 3: a button and a tidy-up macro

Put a button on the Orders sheet (Developer > Insert > Button) and assign CreateInvoices to it (Your first macro: Sub, MsgBox, running it and a button). While testing, you will create many invoice sheets; this small macro removes them again. It loops backwards, because deleting while counting forwards would skip sheets (For loops: For...Next and For Each).

VBA
Public Sub DeleteInvoiceSheets()
    Dim i As Long
    Dim removed As Long
    If MsgBox("Delete all invoice sheets in this workbook?", vbYesNo + vbQuestion) <> vbYes Then Exit Sub
    Application.DisplayAlerts = False
    For i = ThisWorkbook.Worksheets.Count To 1 Step -1
        If Left$(ThisWorkbook.Worksheets(i).Name, 4) = "INV-" Then
            ThisWorkbook.Worksheets(i).Delete
            removed = removed + 1
        End If
    Next i
    Application.DisplayAlerts = True
    MsgBox removed & " sheet(s) deleted.", vbInformation
End Sub
modInvoices: delete all generated invoice sheets (the PDFs stay)

This procedure goes below the others in modInvoices, which already has Option Explicit at the top. To start completely fresh, also clear column F of Orders, set Settings!B1 back to 1 and clear the Log.

Ideas to extend the project

  • Email each PDF to the customer with Outlook, using the address from a new Email column (Control Outlook, Word and PowerPoint from Excel VBA). Use .Display while testing.
  • A UserForm to pick which customers to invoice and the invoice date (UserForms: build a data-entry form in VBA).
  • Templates per language or company chosen from a Settings value.
  • A clsInvoice class holding number, customer and lines, with NetTotal and GrossTotal methods, to separate the calculation from the sheet (Class modules: build your own objects in VBA).
  • Mac support: replace the two dictionaries with Collections and a KeyExists helper, because Scripting.Dictionary does not exist on the Mac. The rest of the code, including the PDF export, works on Excel for Mac, though macOS may ask once for permission to write to the Invoices folder.

Common mistakes in projects like this

  • Increasing the invoice number in memory but saving it only at the end, so a crash causes duplicate numbers on the next run.
  • Writing PDFs before marking the orders, then crashing in between and invoicing the same orders twice. Here the order is PDF, then mark, then counter; a re-run after a crash at worst re-creates a PDF that already exists.
  • Calculating VAT per line and per total with different rounding, so the printed lines do not add up.
  • Referring to ActiveSheet after copying the template; if events or another add-in change the active sheet, the invoice ends up on the wrong sheet. Use an object variable.
  • Forgetting that a hidden template produces hidden copies.

Congratulations

You have reached the end of the VBA course. You can now record and clean up macros, write procedures and functions, work with ranges, sheets, files, tables, charts and pivot tables, handle errors and events, build forms and classes, make your code fast and share it safely. The best way to keep learning is to automate one real, boring task from your own work every week. Start small, test on copies, and keep your code readable.

Check yourself

1. Why does the macro save the next invoice number to the Settings sheet right after each invoice instead of once at the end?

2. How does the macro find the sheet that wsTpl.Copy just created?

3. Why are order lines marked with the invoice number in column F?

4. What happens to customer C999 in the sample data?

5. Why is each line amount rounded before it is added to the net total?