Case study: automate a monthly sales report
Debug and automate11 minPremium
Builds on Repeat steps for every row with For and For Each and Ask and confirm with MsgBox and InputBox.
Every month, the sales coordinator at a tile distributor in Valencia gets the orders as an export, one row per order and a different number of rows each time. Before the regional meeting she bolds the headings, formats the amounts, flags the orders under €1,000 and adds a total row. That's 20 minutes of clicks, and the macro below does it in a second.
How it works
The macro uses one idea from each part of the course:
- It asks first, with a Yes and No message box, since Excel can't undo a macro.
- It finds the last row with
End(, so the report fits however many orders came in.xlUp) - It formats the headings in a
Withblock and the amounts withNumberFormat. - It loops from row 2 to the last row and flags each order under €1,000 with an
If. - It writes the total row under the list, with a SUM formula built from the last row.
Sub BuildMonthlyReport() Dim r As Long,lastRow As Long If MsgBox("Format this month's report?", vbYesNo) = vbNo Then Exit Sub lastRow = Cells(Rows. Count, 1).End( xlUp). Row Range("D1"). Value = "Flag" With Range("A1:D1") .Font. Bold = True .Interior. Color = RGB( 221, 235, 247) End WithRange("C2:C" & lastRow). NumberFormat = "#, ##0. 00" For r = 2 To lastRowIf Cells(r, 3). Value < 1000 Then Cells(r, 4). Value = "Below target" End IfNext rCells(lastRow + 1, 2). Value = "Total" Cells(lastRow + 1, 3). Formula = "=SUM( C2:C" & lastRow & ")" Columns("A:D"). AutoFit End Sub
"=SUM(C2:C" & builds the formula as text: with orders down to row 6, it becomes =SUM(, and the total goes in row 7.
To run it from a button, choose Developer > Insert > Button under Form Controls, draw the button on the sheet, select BuildMonthlyReport in the Assign Macro dialog and select OK. Right-click the button and choose Edit Text to call it Build report. On a Mac, choose Developer > Button.
Common mistakes
Cells(for the total. That's the last order's row, so the total overwrites it; the row under the list islastRow, 2) lastRow +.1 "=SUM(C2:C" &. The formula then takes in its own cell, a circular reference.lastRow + 1 & ")" - A fixed formula such as
"=SUM(C2:C50)". Next month's 80 orders are only partly added up; build the range fromlastRow.
In short
- Ask first, find the last row, format, loop and flag, then add the total under the list.
- Build a formula as text with
&so its range follows the data. - Put the macro on a Form Controls button so anyone can run it.
Practice
Premium5 exercises: 3 macros and 2 sets of steps.
Practice is part of Premium
Every lesson is free to read, and you can practice the free lessons without an account. This lesson's exercises are part of Premium, which you add to a free account.
Have one? Sign in