Ravindra BagaleCourses & study guides मराठी Track your progress

12. Macros and VBA

Practice and Answer Key: A Macro that Tags Late Orders

Goal of this practice: Write a short loop that writes "Late" next to every order over 15 minutes and counts them.

Suppose Raja wants a button that marks late orders (more than 15 minutes) in column J of the Orders sheet and shows how many there are. Use the Module 3 mini dataset in A1:I11. All data is fictional.

Use the Orders sheet: Order ID in column A, Mins in column H, ten data rows (2 to 11).

Exercise (one under the other):

  1. Press Alt + F11, click Insert › Module.
  2. Write a Sub named TagLateOrders.
  3. Find the last row from column A.
  4. Loop from row 2 to the last row. If column H is more than 15, write "Late" in column J, else clear J.
  5. Count the late rows and show the count in a MsgBox.
  6. Save as .xlsm and add a button with Developer › Insert › Button.

Expected result (check your numbers):

About this data. The rows in this practice on A Macro that Tags Late Orders are made up. The people, shops and amounts are fictional, so you can try the steps safely. Any business name here is not a real company.
Row Order ID Mins J
6 AMN-1005 16 Late
8 BLK-1007 18 Late
11 BLK-1010 17 Late

All other rows stay empty in column J. The MsgBox says: Late orders: 3. Check with =COUNTIF(H2:H11,">15").

Answer key (open after you try)
Sub TagLateOrders()
    Dim ws As Worksheet, r As Long, lastRow As Long, n As Long
    Set ws = ThisWorkbook.Worksheets("Orders")
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    For r = 2 To lastRow
        If ws.Cells(r, "H").Value > 15 Then
            ws.Cells(r, "J").Value = "Late"
            n = n + 1
        Else
            ws.Cells(r, "J").ClearContents
        End If
    Next r
    MsgBox "Late orders: " & n
End Sub

Common mistakes:

What you see Why Fix
Nothing happens The macro is in a sheet module or macros are disabled Put it in a standard module and enable macros
"Late" written in the header row The loop starts at 1 Start at row 2
Old "Late" tags stay after the data changes No Else branch Clear column J when the order is on time
Run-time error 9 Sheet name in the code does not match Check the tab is named exactly Orders

Ravindra Bagale's rule: test a macro on a copy of the file first, and step through it once with F8.

Thodkyaat sangaycha tar (quick recap)

Developer tab on, security Disable with notification, file .xlsm; recorder ne shika (absolute vs relative aadhi tharva); code module madhe, Option Explicit, Long aani Set; Select talava, ws.Range vapra; If/Select Case, For/For Each/Do loops, last row khalun varti; macro la Undo nahi – backup theva; UDF value return karto; On Error sathi cleanup; F8 ne debug; roj che macros PERSONAL.XLSB madhe. Aata pudhe jaauya – dashboards!