16. Practice Exercises with Answer Hints
16.11 Module 12: Macros and VBA
Automate a visible action in a workbook you can restore
A teammate wants consistent headers, a reliable last-row message, cleaned city labels and a separate list of sheets. The same workbook may also need a temporary extract with Cancelled rows removed. These are small jobs, but a macro can change more data than a beginner expects if the selected workbook or range is wrong. Define a clear destination and an acceptance test before recording or writing code.
Use the original fictional ten-order fixture in a disposable local copy with Orders, Stores, Products and Report worksheets. The practice code is for an authorized desktop Excel environment with supported VBA. Keep the original file separately. Use the paper-mode walkthrough if you cannot run macros in your environment. It teaches how the code branches without implying that an Excel run took place.
Identify the workbook, worksheet, column and records a procedure can touch. Before running an editing routine, inspect the exact copy and preserve a known good version.
Prepare the environment and a few controlled cases
- Save a separate practice workbook as an
.xlsmfile where the approved VBA environment allows it. Excel for the web cannot run or edit VBA. - Keep the code in the workbook that owns the practice data, using a standard module for the displayed procedures. ThisWorkbook targets the file containing that module.
- Use the 10-row Orders sample with headers in row 1 and Order ID in column A. Create a Table named
tblOrdersfor the removal exercise. - Verify the compared sheet structure. An expected result can change if you add extra data, a different Table name or a formula beyond the given range.
- Keep the recording short and avoid unintended clicks. Inspect the code and test it only on an owned local scratch copy.
Seven original exercises · Work through the inputs and expected changes
1 · Record a green, bold header format and reuse it on another sheet
Record a short formatting procedure for A1:I1 and apply it to a second scratch worksheet with the same intended header range. Verify the first data row was unaffected.
Hint for exercise 1
Use Developer and Record Macro. Store it in your current practice workbook. Select only the nine header cells and record bold plus green fill. Stop before doing unrelated actions.
Worked answer for exercise 1
Save the recording in the macro-enabled scratch workbook, inspect the range and sheet references, and run it on the intended second tab. Expect the new tab's A1:I1 to become bold and green while the recorded values stay unchanged. If the recorded macro activates the first sheet explicitly, adjust the training plan or use a deliberately scoped selection.
2 · Report the last occupied Order ID row
Find the last relevant used row in column A on Orders and show its row number. Predict the result for the original baseline and a new ID on row 12. Distinguish the returned worksheet position from transaction count.
Hint for exercise 2
Start at the bottom cell in column A and use End(xlUp). Check for a missing sheet or empty column separately.
Worked answer for exercise 2
The helper below reports row 11 for the ten source orders under the one header. With a genuine new ID in row 12 it reports 12. It follows column A and does not locate every piece of content on the sheet.
3 · Trim each text city in column C
In an editable scratch copy put ordinary outer spacing around a few City values. Standardize their outer spaces while leaving other columns unchanged. Keep formula cells and errors available for review instead of replacing them with text.
Hint for exercise 3
Loop from row 2 through the last Order ID row. Use VBA Trim on ordinary text values and skip a City cell containing a formula.
Worked answer for exercise 3
A typed Pune becomes Pune and Nashik becomes Nashik. Typed uppercase NASHIK remains uppercase because the procedure trims only exterior spaces. Counts and original amount sums stay unchanged.
4 · Remove all Cancelled rows from a disposable working Table
Copy the original workbook. In the scratch Table, remove records with status Cancelled, and verify the removed IDs and retained original fields. Use a backward loop so a shifted next row is not skipped.
Hint for exercise 4
Loop backward through Table row positions. Read the Status cell before removing that Table row.
Worked answer for exercise 4
BLK-1004 (₹240) and BLK-1009 (₹220) are the only Cancelled records. The result contains eight rows and known amount ₹2,410, including the Returned order ₹195. Delivered-only amount stays ₹2,215. Keep the original ten rows in the preserved input copy.
5 · List existing worksheet names on a new sheet
In a fresh four-sheet scratch copy, add one output worksheet and list the names that were already present. Verify the order and whether your chosen output includes itself. Avoid overwriting an existing results sheet.
Hint for exercise 5
Loop over ThisWorkbook.Worksheets. Create the output after checking the name, then skip the newly added worksheet while listing.
Worked answer for exercise 5
With the specified four original worksheets in that order, expect Orders, Stores, Products and Report. The new SheetNames tab is excluded. If it already exists the example asks you to preserve it and work on another copy.
6 · Build a GSTAmount teaching function
Return entered amount times a practice rate and round to two decimal places. Pass the percentage as a numeric rate, and state which midpoint rounding convention you expect. This is a classroom arithmetic function.
Hint for exercise 6
VBA Round uses banker-style midpoint rounding. Use the worksheet Round method when reproducing the expected Excel worksheet rounding convention.
Worked answer for exercise 6
=GSTAmount(64,18%) gives ₹11.52; =GSTAmount(1,12.5%) gives ₹0.13 with the worksheet rounding method, because 0.125 rounds upward at two decimals under this rule. With VBA Round alone, the exact midpoint example would give 0.12.
7 · Explain a friendly error if Orders is unavailable
Run the row-check routine against a scratch copy where the Orders tab is temporarily renamed, or trace its behavior on paper. Confirm how it distinguishes a missing expected worksheet from other failures.
Hint for exercise 7
Use an On Error GoTo block around the operation, inspect the expected missing-sheet error and provide a clear message. Exit after the success path so it does not fall into error handling.
Worked answer for exercise 7
With the expected sheet renamed, the sample reports that Orders is missing. Restoring the correct name returns the normal row message. Other unexpected errors report review information without claiming the operation worked.
Qualify the scope and check the last row explicitly
An unqualified Cells reference can read from whichever sheet is currently active. That is hard to predict when another workbook is open. Capture the exact worksheet from ThisWorkbook in a variable and qualify both Rows.Count and Cells with it. Check that your standard module really is in the local practice file rather than a personal or different workbook.
Trace a position with a gap and a false footer
Imagine an exercise copy where there are real IDs at A2 and A5 but A3:A4 are blank. The last occupied position is 5, while the number of records is two. A loop that visits positions 2–5 needs a valid order-key test if it will act only on rows representing purchases. Our trim routine checks the meaningful extent under the original contiguous fixture. For a wider workbook, a footnote in A15 or a formula returning empty text can extend the occupied area without adding a real ID. Decide which rows should be inspected before treating the last row as an audited order boundary.
An Excel Table separates data records, headers and totals. For a script that needs the Table's existing records, its collection of ListRows can be clearer than scanning a whole worksheet when loose cells follow below. The last occupied-column exercise intentionally shows the lower-level approach and why it has assumptions. A robust code review calls out those assumptions and tests an ordinary boundary and a deliberate exception. This helps a learner avoid treating one correct returned number as a universal method.
Report scope, empty data and unexpected errors separately
Option Explicit
Public Sub ReportLastOrderRow()
Dim wb As Workbook
Dim orders As Worksheet
Dim lastRow As Long
Set wb = ThisWorkbook
On Error GoTo MissingOrders
Set orders = wb.Worksheets("Orders")
On Error GoTo ReadFailed
If Application.WorksheetFunction.CountA(orders.Columns(1)) = 0 Then
MsgBox "Column A is empty.", vbInformation
Exit Sub
End If
lastRow = orders.Cells(orders.Rows.Count, 1).End(xlUp).Row
If lastRow = 1 Then
MsgBox "Column A has no ID below the header.", vbInformation
Else
MsgBox "Last occupied ID row: " & lastRow, vbInformation
End If
Exit Sub
MissingOrders:
If Err.Number = 9 Then
MsgBox "The expected Orders worksheet is missing.", vbExclamation
Else
MsgBox "Could not open the Orders worksheet. " & Err.Description, vbExclamation
End If
Exit Sub
ReadFailed:
MsgBox "Could not inspect the ID column. " & Err.Description, vbExclamation
End Sub
Use Option Explicit once at the top of the standard module if combining the examples. The code uses a named source and scoped messages. The empty case reports a different fact from a header-only column. The expected last occupied ID row is 11. If row 8 is blank but row 11 contains an ID, the returned position remains 11. Counting records then requires counting actual eligible ID cells. The routine assumes the normal practice worksheet size and no deliberate value in the very last grid row.
Record narrowly and inspect the range before reuse
A macro recorder captures the actions you perform. Prepare the destination workbook and select the required nine header cells deliberately before styling. Set the current practice workbook as the location for the recording, then stop after the bold and fill actions. Avoid mixing navigation, saving, workbook closure or other actions into that first recording. For this task the header row's underlying text should be unchanged. Compare one amount below the header and one title cell before and after the run.
Read the recorded worksheet selection
Find the generated procedure in the Visual Basic Editor of the practice file. Note whether it activates a particular sheet or refers to a specific range. A recorder can capture a selected sheet or the current selection, depending on how you operated it. If you want to reuse the exercise on the Report tab, confirm which cells the existing code will touch. One direct alternative is to name Report and the expected header address explicitly afterward. That route behaves the same even if Orders is visible when the button is run.
Public Sub FormatReportHeader()
Dim report As Worksheet
Set report = ThisWorkbook.Worksheets("Report")
With report.Range("A1:I1")
.Font.Bold = True
.Interior.Color = RGB(198, 239, 206)
End With
End Sub
The RGB arguments represent color components for the chosen green. This compact written procedure is an optional controlled alternative after inspecting the recorded version. It formats Report only. Sheet title, input range and first data row should remain unchanged. There is no need to assign a keyboard shortcut until you can inspect the full effect. If you do assign one, note that a macro shortcut may override an ordinary Excel shortcut while the workbook is open.
Verify a repeat run
Reapplying the same bold and green styles to the known range should leave the displayed header in the same condition. That repeat test is easy to compare with a routine that adds another row or fresh sheet each run. The same visual result can be safe to repeat for the first procedure, whereas a second insert may be unexpected. Write what repeating each macro is supposed to do. Record ordinary value preservation alongside the style check.
Guard a text change and an isolated deletion differently
Trim ordinary outer spaces without replacing formulas
Use ThisWorkbook.Worksheets("Orders") in the scratch file, column C as City, and column A for last occupied ID. The model assumes the nine source headers are on row one. The code below checks the value type, leaves calculated City formulas intact, and uses VBA Trim on text. It addresses the ordinary outer spaces planted for this exercise. It does not collapse repeated interior spaces like Excel's worksheet TRIM, and other invisible characters require separately verified rules.
Public Sub TrimPracticeCities()
Dim orders As Worksheet
Dim cityCell As Range
Dim r As Long
Dim lastRow As Long
Dim rawValue As Variant
Dim reviewedValue As String
Set orders = ThisWorkbook.Worksheets("Orders")
lastRow = orders.Cells(orders.Rows.Count, "A").End(xlUp).Row
For r = 2 To lastRow
Set cityCell = orders.Cells(r, "C")
rawValue = cityCell.Value2
If VarType(rawValue) = vbString And Not cityCell.HasFormula Then
reviewedValue = Trim$(CStr(rawValue))
If reviewedValue <> CStr(rawValue) Then cityCell.Value2 = reviewedValue
End If
Next r
End Sub
Read the code as a boundary. It never writes the header, Order ID or Amount. If a row has an Excel error value, VarType does not mark it as a string, so the inner conversion is skipped. A real import might use case or nonbreaking spaces with intentional cultural names or abbreviations. Review those values using a more explicit input policy. The original exercise does not ask you to make every city uppercase or infer unknown mappings.
Use stable IDs and Table rows for the disposable deletion exercise
Keep Order IDs and amounts for the two original Cancelled rows in your notes before running any deletion. The Table script deletes within the scratch Table rather than dropping entire worksheet rows. Run it only on the intended disposable practice copy. The starter source has a recognized status called Cancelled. The sample normalizes ordinary outer spaces and compares text case-insensitively. A missing or unexpected status stays for review.
Public Sub RemoveCancelledScratch()
Dim wb As Workbook
Dim orders As Worksheet
Dim practiceTable As ListObject
Dim statusColumn As Long
Dim i As Long
Dim statusValue As Variant
Set wb = ThisWorkbook
Set orders = wb.Worksheets("Orders")
Set practiceTable = orders.ListObjects("tblOrders")
statusColumn = practiceTable.ListColumns("Status").Index
If MsgBox("Remove Cancelled rows in this scratch workbook? " & wb.Name, _
vbYesNo + vbQuestion + vbDefaultButton2) <> vbYes Then Exit Sub
For i = practiceTable.ListRows.Count To 1 Step -1
statusValue = practiceTable.ListRows(i).Range.Cells(1, statusColumn).Value2
If VarType(statusValue) = vbString Then
If StrComp(Trim$(CStr(statusValue)), "Cancelled", vbTextCompare) = 0 Then
practiceTable.ListRows(i).Delete
End If
End If
Next i
End Sub
Start with a clear worksheet view so that an unintentionally filtered selection doesn't hide the exercise records from your review. The loop above addresses all rows in the named Table. It does not limit the scan to visible positions. If you ever modify it to operate only on a selected report population, write the in-scope criteria explicitly. An ordinary worksheet filter alone is not a guard for this procedure.
In a four-record scratch thought experiment, statuses are Delivered, Cancelled, Cancelled, Delivered. Removing the second record first can move the next Cancelled record up into its just-processed position. A loop that immediately advances can miss it or exceed the shortened data boundary. Iterating backward visits the original third before second. The earlier row positions remain available. In the original ten-row sample the two Cancelled rows are not adjacent, so the extra test is a useful proof that your implementation does not merely pass the ordinary case by chance.
Verify Table scope and expected permitted changes
The Table's Status field can move when columns are reorganized. The macro reads its column position by name rather than assuming it is the ninth Table column. Check the field name and which Table owns that position. Worksheet column I is the supplied baseline location, while a Table can begin elsewhere. Verifying the exact Table and column before removal gives you a way to avoid touching another list with similar-looking data.
Try the no-match case in a thought experiment. If no Status value equals Cancelled under the defined trim and case rule, the loop should leave the original Table unchanged. If the Table has no data rows, the count is zero and the backward loop has no valid position to inspect. In both cases compare actual source row count. Under the valid baseline with two cancellations, a second run should find none left. Keep the removed IDs and statuses in a test note rather than trying to infer how many were removed from a later success message.
If a sheet is protected from row changes, use the separate authorized disposable copy prepared for this exercise. A failing action can leave the workbook in an expected or partially edited state, depending on which prior actions succeeded. Do not use a failed trial to infer all original records remain. Compare with the saved input and restart a new test copy if you need to repeat the exercise from the original population.
Keep a separate test if deletion is not required in your actual workflow. An Advanced Filter, Table filter or Power Query result can furnish an independently verifiable subset while preserving source rows. The guided exercise deliberately practises editing a disposable Table. It provides the distinct outcome: 10 raw originals, eight remaining working rows and ₹2,410, with the data-preserving original still available.
Write a bounded output and a testable worksheet function
List worksheets into a new named destination
The Worksheets collection iterates worksheets in the owned workbook. Decide whether to also list other sheet types in a different exercise. Here the goal is to list the four worksheets present before the new report is added. Check if SheetNames already exists, then make a new tab at the end of the workbook's worksheet sequence and write the names. The procedure keeps old evidence by stopping when the output exists. It does not replace an earlier result.
Public Sub ListPracticeWorksheetNames()
Dim wb As Workbook
Dim ws As Worksheet
Dim nameSheet As Worksheet
Dim outputRow As Long
Set wb = ThisWorkbook
For Each ws In wb.Worksheets
If StrComp(ws.Name, "SheetNames", vbTextCompare) = 0 Then
MsgBox "SheetNames already exists. Use a fresh practice copy.", vbInformation
Exit Sub
End If
Next ws
Set nameSheet = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.Count))
nameSheet.Name = "SheetNames"
nameSheet.Columns(1).NumberFormat = "@"
nameSheet.Cells(1, 1).Value2 = "Worksheet"
outputRow = 2
For Each ws In wb.Worksheets
If Not (ws Is nameSheet) Then
nameSheet.Cells(outputRow, 1).Value2 = ws.Name
outputRow = outputRow + 1
End If
Next ws
End Sub
The output argument points to the worksheet after the current last worksheet in this simple workbook. The new destination is a separate worksheet and the code writes only its first column. The report excludes itself so there are four names in the expected setup. With extra worksheets present, it reports each of those too. Reconcile results with the actual original tab set and test the repeated-run stop. A workbook with a chart sheet named SheetNames is outside this provided four-worksheet fixture; broader workbook code would check conflicts across Sheets.
Prove which method rounds a midpoint
Public Function GSTAmount(ByVal amount As Double, ByVal rate As Double) As Double
GSTAmount = Application.WorksheetFunction.Round(amount * rate, 2)
End Function
Type the demonstrated function in a standard module and call it in an ordinary worksheet cell within the compatible macro-enabled scratch workbook. For this exercise use the worksheet Round convention. A deliberately chosen 0.125 midpoint makes the difference visible. At two decimals the worksheet returns 0.13. The native VBA Round function instead uses a banker-style midpoint policy that yields 0.12 in that exact example. Choose the behavior required by the task and double-check midpoint arithmetic before comparing different workbooks.
Define where rounding belongs
With the chosen worksheet rule, two independent calculations of 0.125 each round to 0.13 each, adding to 0.26. If a policy requires summing the original products first, 0.125 plus 0.125 gives 0.25, and rounding the combined amount to two decimals stays 0.25. Both calculations use the same midpoint rule, and the timing of rounding creates the difference. Make that difference visible in the result specification before comparing a worksheet function and a report subtotal.
For the original 64 × 18% test, there is no need to use a tax table or an external reference. Write the two inputs and expected 11.52 within the local workbook. Compare a known zero or a midpoint separately. If a reader needs to recognize the unit, add a cell format or a label outside the arithmetic, leaving the function's result numeric. This keeps the lesson reproducible and avoids letting a formatting choice dictate the type a later formula receives.
The function has a narrow job. It returns a number and doesn't format a cell, fetch a rate or change another record. Numeric rate 0.18 is the same intended input as entering 18% in a worksheet, while typing plain 18 multiplies the amount by 18. Validate the intended input and choose formatting separately. For a recorded output zero is a valid product if approved amount or rate is zero. A missing expected input needs its own validation before handing that case to this simple function.
Predict what the row cleanup touches
Confirm the workbook and Table
Use the local scratch workbook containing the code. Check it has the Orders worksheet, the named Table and the ten original order IDs.
Identify the exact removal population
The baseline Cancelled records are BLK-1004 and BLK-1009. Amounts are ₹240 and ₹220. Keep the original file unchanged.
Inspect the list in descending row order
Check each status and start from the Table's bottom. A removed later row doesn't deprive the next earlier position of its record.
Reconcile the scratch state
Eight rows remain at ₹2,410. The Returned order stays and Delivered total is still ₹2,215. Compare actual IDs, not just the display.
Lab 1 · Format the intended worksheet and diagnose last-row messages
Prerequisites. Use the four-sheet local practice workbook and a functioning authorized Excel desktop client, or a paper trace. Preserve a separate original copy. Make sure no production workbook or unknown macro is involved.
- Record the green and bold header operation, stop recording and inspect what the code does. Check scope before running it on the Report tab or using the explicit alternative.
- Verify the nine target header cells and compare one adjoining data row. Record whether the original values are intact and the expected green and bold settings changed only the planned range.
- Use the last-row procedure with the proper Orders sheet. Check the expected row 11 in baseline and row 12 under a new appended ID. The result should not change solely because another worksheet is active.
- Change no original file. In scratch rename Orders to an alternate name and run the row check or trace the intended error branch. Expect the specific friendly missing-sheet message. Restore the worksheet name.
- Build a separate empty-column and header-only test. The empty case checks CountA; the header-only case finds position 1 and reports no ID below the header. Compare the outcome with a two-record dataset that has a gap.
- Test after restoring the original ten records. Save the known successful output and observation log in a separate local practice copy.
Expected result. The recorder and explicit references affect only the intended range. The expected message distinguishes the normal, missing and empty states. Last row is useful for finding a boundary and remains separate from the count of transactions.
Troubleshoot. If formatting reaches the wrong tab, inspect the recorded code and workbook storage choice. If the expected macro is missing after saving, verify the file extension and supported client. If any macro is disabled by your environment, use the paper method and document actual test evidence.
Finish. Keep one authorized test copy and restore accidental style or sheet name edits. Avoid running the exercises with other sensitive spreadsheets open.
Lab 2 · Check text cleanup, safe selection and arithmetic behavior
Prerequisites. Use separate working copies for trim, removal and list tests so their outputs do not accidentally affect each other. Keep the original ten source rows and scope visible. A paper check can reproduce the intended branches if the app cannot run VBA.
- Add controlled ordinary outside spaces to two City values and leave the raw source intact. Run or trace the trim procedure. Verify Pune and Nashik are readable and the 10 ordered amounts still total ₹2,870.
- On separate scratch run the Cancelled removal routine after checking the prompt and named Table. Expect those two IDs gone, eight records and ₹2,410. Compare a known retained Returned row so status filtering isn't confused with Delivered-only.
- Reason through or reproduce the adjacent cancellation case with four synthetic status rows. Compare the retained first and fourth records when iterating backward. Keep source and test copies separate.
- Run the names routine on a clean four-sheet scratch copy. Verify the four exact names and try a second invocation. Expect an existing-output message without another write. If you cannot run VBA, check the intended loop with the original sheet sequence.
- Call the classroom function on numeric 64 and 18%, and exact midpoint result 0.125. Verify 11.52 and 0.13 under the worksheet rounding policy. Compare the exact midpoint with a separately reasoned native VBA Round example.
- Record which operations edited data, which only report a result and which returned a value to a formula. Restore the disposable copy after documenting the state changes.
Expected result. The text cleanup and selection affect only the intended fields and records. Workbook output is auditable and the function is testable from mathematical examples. The testing results specify whether they were runtime observations or a trace.
Troubleshoot. If row or column behavior looks unexpected, inspect the typed value and actual row positions. If a row was skipped, check iteration order and status text. If two rounding outcomes disagree, review the implementation and declared midpoint policy. When diagnosing errors, use an approved stepping command in the code editor instead of executing many unfamiliar actions at once.
Finish. Preserve the intact source and keep deliberately changed examples in a marked practice file. Record exact behavior and avoid replacing an earlier checked output during retesting.
Trace the code before trusting its workbook effects
A short procedure is easier to evaluate when you can name every input and effect. The formatter reads a specific worksheet and writes two style properties. The row procedure reads one column and displays a message. The trim procedure may replace literal City text. The deletion procedure changes membership in an isolated Table. The sheet report creates one tab. The UDF returns an ordinary numeric value to an Excel formula. Describe these jobs separately when reviewing what could happen after choosing a macro.
Find the first wrong object or input with a narrow test
If a message gives an unexpected final row, check first which workbook ThisWorkbook refers to and whether Orders is the actual intended sheet. Then inspect its ID column, including accidental content or a formula that displays an empty string below the genuine records. COUNTA counts empty text results of formulas as present values. End(xlUp) identifies a worksheet position under the data layout used here. A blank-looking formula or a footer below the valid entries can make the row unrelated to the last approved order. A structured Table with reviewed key values can provide a better record count and boundary for another workbook.
Begin macro troubleshooting with a paper line trace or a supported step command in the Visual Basic Editor. Watch the local variable for the intended worksheet, the row number before entering a loop, and the two possible first decisions. For example, if the sheet name resolves and the ID column isn't empty, the routine proceeds to the last row. If the named sheet is absent, Err.Number identifies the expected missing item and the message stops. Do not let the error handler silently continue to a later data edit with an unassigned worksheet.
Distinguish two types of success evidence
A completed procedure shows that its code returned from the run. A correct business outcome requires a separate observation. The header looked green because a property changed, but perhaps the wrong Tab was active. The report listed four names, but perhaps two belonged to a different workbook. Verify target and output against a known standard. Use the original four sheet names and two adjacent header/data cells as direct controls. Choose a test that would fail even when the command itself returned normally.
Apply the same method to worksheet edits. If the cancelled subset was removed, the surviving approved Table must still include the Returned order AMN-1008. Amount is ₹2,410 after the two cancellations are excluded, not ₹2,215. The difference is ₹195. If the result contains only seven orders and ₹2,215, the procedure likely removed more than intended. Read the status check and inspect actual surviving IDs. Report correct original amount, affected IDs and remaining status mix before calling it complete.
Some changes can fail partway. For example a later Table deletion might fail due to a protected range after an earlier operation already succeeded. A message about failure doesn't mean the workbook returned to its prior state. That's why the editing lab uses a disposable copy and compares actual records. Preserve it temporarily for debugging if useful, then rebuild the scratch file from the known original before retrying. Keep report tests different from data-changing macro tests.
Write an observation log the next learner can reproduce
- Record the workbook and worksheet contract, including any expected Table names and columns. Describe what an appropriate confirmation should show.
- Record expected untouched areas such as original headers, amount values during text trim, and the original source file during testing. Check each after the exercise step.
- Record a known success case and a known failure path, for instance an expected missing Orders tab or a new report name conflict.
- Record whether the app executed the procedure, whether you inspected a generated recording or whether you traced the intended behavior manually.
- Preserve a way to compare the starting and ending row sets, avoiding real customer information or sign-in details in your exercise output.
Protect the test evidence when adding another macro
Use one standard module with Option Explicit at its top. Variable declarations let you distinguish a worksheet object, a value from a cell and a count used in a loop. If a misspelled object name returns a run-time error, inspect where the assignment failed. Option Explicit catches undeclared variable names at compilation, but it cannot find whether a workbook really has a worksheet named Orders. A compile check and a live object check serve distinct purposes. Spell worksheet and Table names exactly under the documented fixture.
Run one small procedure at a time. The header formatting and name-report tests do not need to follow deletion. A macro that changes the source can influence another macro's expected last-row result. In the original baseline after removing two data rows, a contiguous Orders table may have eight detail rows and header one. However, independent content below it can still change the last occupied position. Use separate fixture variants and label which output each test is intended to exercise.
Keep approved outputs distinguishable by filename and report label. If you generate SheetNames on one copy, record that exact copy before trying the name conflict. If the worksheet itself was manually renamed, preserve the current evidence rather than using a newly generated copy to claim the previous report passed. State the action that was really taken along with the expected value. These habits transfer directly to testing other workbook automations.
Check a failed precondition using the benign worksheet-list routine. On a fresh four-sheet copy the result has four names. After successful output you can place a harmless test note beside the generated list and invoke the procedure again. The precondition should preserve the existing sheet and note. This demonstrates the difference between a stopped action and a failed write. If running in paper mode, mark the sheet already existing at the top of the routine and trace the early exit before any new worksheet is added.
Use the same principle when reviewing the first formatting macro. If the intended Report sheet does not exist, resolve that workbook structure difference before running any alternative on another active sheet. When the scope is clear, the formatting should update only the named header cells while their existing text and the second worksheet's independent data remain available for review. Compare the two worksheets after saving the expected scratch output.
Recall without reading the code. Which procedure reads without editing, which one creates an output sheet, and what proves that the cancellation routine changed precisely the intended records?
Check why the last row and order count differ
Worksheet row 11 includes one header and ten data records under the contiguous baseline assumption. In a sheet with gaps, the last position still identifies a boundary, but its number no longer directly gives counts.
Check why bold green formatting has its own review
A recording can activate the wrong sheet or include an unrelated action. Check actual destination and preserved values.
Check what a backward loop protects
Removing a later row allows earlier indices to stay available for the next backward iteration, including adjacent Cancelled rows.
Check what amount the removal should preserve
After excluding ₹240 and ₹220, total remaining is ₹2,410, which still includes the Returned ₹195 record.
Quiz · Choose the correct scope and check
1. Which workbook does ThisWorkbook identify? A. The file containing the code. B. Any visible worksheet. C. The last workbook opened.
A. It refers to the workbook where the procedure is running from. Check the module is in the intended practice file.
2. What is the last baseline Order ID row? A. 10. B. 11. C. 12.
B. Ten source rows follow the header at row 1.
3. Why iterate from the last Table row back to the first? A. It preserves earlier positions after deleting later rows. B. It converts all dates. C. It selects the last workbook.
A. Forward deletion can shift an unchecked adjacent record into the position already inspected.
4. Which amount is left after only Cancelled records are removed? A. ₹2,215. B. ₹2,410. C. ₹2,870.
B. The Returned record still contributes ₹195 alongside delivered records.
5. Which process returns ₹0.13 on the exact 0.125 midpoint case? A. The lesson's worksheet Round method. B. Native VBA Round to even at 2 places. C. Removing the amount row.
A. The worksheet rounding policy produces 0.13; native VBA Round gives 0.12 in this specific example.
6. Which is evidence of appropriate error handling? A. The missing Orders scenario gives a clear specific outcome and the success path remains independent. B. Every failed result shows success. C. The routine hides all messages.
A. The documented expected failure and the normal result should be separately observable.
Interview practice
- How would you safely test a recorded macro?
- I record only the desired action in an authorized scratch workbook, inspect its sheet and range, then verify both changed and unchanged cells.
- Why qualify Cells and Rows.Count?
- I want to search the exact target sheet independently of the currently active workbook or worksheet.
- What can last row tell you about a dataset?
- It identifies a worksheet boundary under the declared column rule. It is separate from eligible order counts, especially if there are gaps or other values.
- How do you avoid skipped deletions?
- I trace the intended row condition and iterate backward through the local scratch list. I verify the remaining stable IDs and known money separately.
- What does your rounding test teach?
- VBA and worksheet rounding can differ at a midpoint. I explicitly choose the policy and demonstrate one exact test where their outcomes differ.
- What should an error message communicate?
- It should identify the attempted operation and help find the actual missing sheet, data or file state. I avoid claiming success or assuming a partial change rolled back.
Revision cards
- Scope. Name the intended workbook, worksheet and range before running a procedure.
- Position. A last occupied row helps locate an edge. Count actual eligible records independently.
- Text edit. Choose an explicit input policy and preserve formulas and unrelated fields.
- Backward loop. Visit adjacent records reliably while editing a disposable Table.
- Rounding. Test an exact midpoint from both worksheet and VBA policies.
- Error handling. Verify both the expected failure and successful outcome on a safe practice copy.