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

12. Macros and VBA

Excel

12.12 Practical Macros on Our Data

Aarti needs a clean morning report, a view for each delivery city and one reconciled set she can compare with the original ten orders. Start with a copy, give each macro a known output and verify the keys as well as the totals. None of the procedures in this lesson deletes a worksheet or clears another user's data.

Decide which copy owns each action

Work from a complete set of independent checks

FreshGo is a fictional delivery training team. The course order data uses labels from a Blinkit and Amazon Now example; the figures and workflow are made up. We reuse the same records so you can already calculate the expected totals: 2,870 in recorded amount across ten orders, 544 across four Pune rows and 360 across two Nashik rows. The task is to prepare a view without changing the source, then prove that the city groups recombine to the same ten individual records.

The ten original Orders rows feed a formatted Report and separate city snapshots. CombinedReview must reconcile ten keys and 2870 rupees.
Give every output a name and scope. Keep your independent evidence where a later run cannot overwrite it.
  • Orders: Keep the original IDs, dates, city strings, amounts and statuses in A1:I11. A city input can gain stray spaces during export. Preserve the original data so a new report can still be compared against it.
  • Report: A practice output copy can set readable dates and amounts, and display a cleaned city in a new column J. It can keep a timing flag in K. This is a prepared snapshot, so source changes will need a new preparation run. No report label should make a cancelled order appear as a timely delivery.
  • City snapshots: Six pre-created practice tabs have known names and reserved A1:I11 areas. Each snapshot starts with the same header. Only the belonging records are populated beneath it. The program can fill the complete reserved rectangle, including blank positions left after the last record for that city.
  • CombinedReview: A final pre-created output worksheet reads only the six intended snapshots. A check uses original IDs and all their original fields. A repeated or missing ID, wrongly grouped row or changed field blocks that final write. Unrelated sheets are outside its input list.

Choose a consistent kind of equality

Moving ten rows from the source into six groups and back should preserve each input record, regardless of its new position. A row count of ten alone is insufficient. One dropped order and one duplicate still make ten rows, and a duplicated row might even be the same amount as the missing one. Keep the ID as the record key. Compare each field to its original under the agreed representation, then compare the gross sum. The values are financial examples in one currency, so the arithmetic is meaningful without converting between price units.

Here an output is only considered ready when a small reconciliation can be explained. Each dataset below is a known fixture. If a new column or a different number of rows arrives, identify the required worksheet and bounds deliberately before reusing the same procedures. Do not change the source to make an output test pass. Fix the intended procedure or revise the teaching workbook layout in a separate copy.

Remember: A formatted view, a city snapshot and a reconciled combined view serve different readers. Verify each output's specific values, ownership and freshness.

Build the training workbook from the original records

Put the exact fields in their expected columns

Save a clean practice file named ReportPractice.xlsm and create an Orders sheet. Use the full ten-row course dataset, with the headers Order ID, Date, City, Platform, Category, Qty, Amount, Mins and Status in row one. Use actual Excel dates and numeric amount and minute cells in that fixture. The table below shows the fields that drive this lesson's routing. For columns B, D, E and F copy the matching values from the original dataset. The module copies those values too.

Relevant source fields from Orders in row order
RowOrder IDCityAmountMinsStatus
2BLK-1001Pune649Delivered
3BLK-1002Nashik27012Delivered
4AMN-1003Pune11014Delivered
5BLK-1004Nagpur24011Cancelled
6AMN-1005Kolhapur23216Delivered
7BLK-1006Pune1508Delivered
8BLK-1007Solapur129918Delivered
9AMN-1008Sambhaji Nagar19510Returned
10BLK-1009Pune22013Cancelled
11BLK-1010Nashik9017Delivered

Create a blank worksheet named Report and one named CombinedReview. Later you will make the six group tabs. Put a separate marker on an extra Notes worksheet, and add a marker to Report M2. The report code writes A1:I11 and J1:K11. Its font and formatting changes stay in the reserved report area. The city and combined snapshot areas are A1:I11 on their own tabs. Keep any proof formulas in another area, and keep an original backup.

Lab one. Produce a report and preserve the raw city

Prepare the output range and one narrow helper

Open Developer Visual Basic in your practice workbook. Use one standard module for the code from both labs, with Option Explicit first. The data loader checks the visible schema and known size. It tests for missing or repeated sample IDs and an actual numeric amount. The report receives a snapshot of all nine source columns. A second block supplies the cleaned city and timing flags, leaving the raw city in the report copy as a separate field. This allows a reviewer to compare the two without changing Orders.

Option Explicit

Private Function LoadPracticeOrders(ByRef data As Variant) As Boolean
    Dim source As Worksheet
    Dim headers As Variant
    Dim rowNo As Long, colNo As Long, earlier As Long
    Dim key As String

    Set source = ThisWorkbook.Worksheets("Orders")
    data = source.Range("A1:I11").Value2
    headers = Array("Order ID", "Date", "City", "Platform", "Category", _
                    "Qty", "Amount", "Mins", "Status")

    For colNo = 1 To 9
        If VarType(data(1, colNo)) <> vbString Then Exit Function
        If CStr(data(1, colNo)) <> headers(colNo - 1) Then Exit Function
    Next colNo

    For rowNo = 2 To 11
        For colNo = 1 To 9
            If IsError(data(rowNo, colNo)) Then Exit Function
        Next colNo

        If VarType(data(rowNo, 1)) <> vbString Then Exit Function
        If VarType(data(rowNo, 7)) <> vbDouble Then Exit Function

        key = CStr(data(rowNo, 1))
        If Not (key Like "BLK-####" Or key Like "AMN-####") Then Exit Function
        For earlier = 2 To rowNo - 1
            If CStr(data(earlier, 1)) = key Then Exit Function
        Next earlier
    Next rowNo

    If Not IsEmpty(source.Range("A12").Value2) Then Exit Function
    LoadPracticeOrders = True
End Function

Private Function CleanPracticeCity(ByVal raw As String) As String
    Dim noBreak As String
    noBreak = Application.WorksheetFunction.Unichar(160)
    CleanPracticeCity = Application.WorksheetFunction.Trim(Replace(raw, noBreak, " "))
End Function

The private loader is called before output writes and fills the supplied array variable through ByRef. Its Boolean result is True only at the last line. The loop comparing an ID with the earlier rows handles duplicate IDs within the ten-row exercise. A12 must be empty so an ordinary appended eleventh record cannot silently go through this fixed-size lab. A general importer also needs a full dynamic boundary check and would have to catch data beyond gaps. Here the ten source rows and their exact columns are deliberate prerequisites.

Public Sub FormatDailyReport()
    Dim data As Variant, notes(1 To 11, 1 To 2) As Variant
    Dim report As Worksheet
    Dim rowNo As Long, state As String, elapsed As Variant

    If Not LoadPracticeOrders(data) Then
        MsgBox "Check the fixed source layout, ten IDs and numeric amounts."
        Exit Sub
    End If
    Set report = ThisWorkbook.Worksheets("Report")
    If report.ProtectContents Then
        MsgBox "Use the prepared Report practice sheet."
        Exit Sub
    End If

    notes(1, 1) = "Clean City"
    notes(1, 2) = "Timing"
    For rowNo = 2 To 11
        If VarType(data(rowNo, 3)) = vbString Then
            notes(rowNo, 1) = CleanPracticeCity(CStr(data(rowNo, 3)))
        Else
            notes(rowNo, 1) = "Review city"
        End If

        state = ""
        If VarType(data(rowNo, 9)) = vbString Then
            state = UCase$(Trim$(CStr(data(rowNo, 9))))
        End If
        elapsed = data(rowNo, 8)

        If state = "CANCELLED" Or state = "RETURNED" Or state = "PENDING" Then
            notes(rowNo, 2) = "Timing not applicable"
        ElseIf state <> "DELIVERED" Then
            notes(rowNo, 2) = "Review status"
        ElseIf VarType(elapsed) <> vbDouble Then
            notes(rowNo, 2) = "Review minutes"
        ElseIf elapsed < 0 Then
            notes(rowNo, 2) = "Review minutes"
        ElseIf elapsed > 15 Then
            notes(rowNo, 2) = "Late"
        Else
            notes(rowNo, 2) = "On time"
        End If
    Next rowNo

    report.Range("A1:I11").Value2 = data
    report.Range("J1:K11").Value2 = notes
    With report.Range("A1:K1")
        .Font.Bold = True
        .Font.Color = RGB(255, 255, 255)
        .Interior.Color = RGB(33, 115, 70)
    End With
    report.Range("B2:B11").NumberFormat = "dd-mm-yyyy"
    report.Range("G2:G11").NumberFormat = "#,##0.00"
End Sub

Verify two results that are easy to confuse

  1. Run FormatDailyReport from your own code workbook. Inspect the heading, date display and numeric Amount values. G2 still contains 64, although it can display 64.00. Add a separate check such as SUM on the ten copied G cells. Expect 2,870, matching the source. M2 and the Notes marker should remain.
  2. In your isolated Orders data, replace the city label in C2 with Pune surrounded by ordinary spaces. Run again and verify the report shows the raw text in column C and Pune in J2. Try the two-word label on row nine, restoring its normal spelling after comparing J9.
  3. For a nonbreaking-space test on row nine, set its source to the demonstration formula below in the practice copy. The raw text contains Unicode space 160. The helper converts it to an ordinary space, then Excel's Trim function collapses any repeated ordinary internal spaces and trims the ends. Check the plain label Sambhaji Nagar in J9. The original formula remains in Orders. The Report holds its evaluated value. Restore the original text before the split test.
  4. Check K6, K8 and K11. These are the three Late delivered rows. Check K5, K9 and K10 separately, because cancelled and returned records are recognized as Timing not applicable. A correct late flag count does not establish that every other row was classified correctly.
  5. Run again without changing input. The reserved ranges receive the same values, with no new worksheet or duplicate row. This lab does not modify pane settings or replace conditional formatting. You can freeze the top row separately in your own view if needed. Keep the marker on the output to confirm the procedure did not require a whole-sheet reset.
Orders C9: ="Sambhaji"&UNICHAR(160)&"Nagar"

Lab two. Build six views and reconcile their contents

Reserve only the named practice areas

Create six blank worksheets with the exact names in the order below. Use the same names in the code. The procedure splits the ten-row exercise into these already prepared tabs. It does not rename, delete or create any worksheet. This lets you choose which areas may receive results before running. Do not use an existing city worksheet containing a separate report. Reserve A1:I11 in each tab so rewriting the rectangle is expected, and keep your proof formulas outside it.

City_Pune
City_Nashik
City_Nagpur
City_Kolhapur
City_Solapur
City_SambhajiNagar
Pune contains four records and 544 rupees, Nashik contains two and 360, and the four other groups contain one each totaling 1966.
Reconcile the group sizes and recorded amount. Also check which order IDs make up the groups.
Private Function CityLabels() As Variant
    CityLabels = Array("Pune", "Nashik", "Nagpur", "Kolhapur", _
                       "Solapur", "Sambhaji Nagar")
End Function

Private Function CitySheets() As Variant
    CitySheets = Array("City_Pune", "City_Nashik", "City_Nagpur", _
                       "City_Kolhapur", "City_Solapur", "City_SambhajiNagar")
End Function

Public Sub SplitByCity()
    Dim data As Variant, names As Variant, labels As Variant
    Dim targets(0 To 5) As Worksheet, nextRow(0 To 5) As Long
    Dim groups(0 To 5, 1 To 11, 1 To 9) As Variant
    Dim block(1 To 11, 1 To 9) As Variant
    Dim g As Long, rowNo As Long, colNo As Long, city As String

    If Not LoadPracticeOrders(data) Then
        MsgBox "Check the fixed Orders practice layout."
        Exit Sub
    End If

    names = CitySheets()
    labels = CityLabels()
    For g = 0 To 5
        Set targets(g) = ThisWorkbook.Worksheets(CStr(names(g)))
        If targets(g).ProtectContents Then
            MsgBox "Use the prepared city output sheets."
            Exit Sub
        End If
        nextRow(g) = 2
        For colNo = 1 To 9
            groups(g, 1, colNo) = data(1, colNo)
        Next colNo
    Next g

    For rowNo = 2 To 11
        If VarType(data(rowNo, 3)) <> vbString Then GoTo UnknownCity
        city = CleanPracticeCity(CStr(data(rowNo, 3)))
        For g = 0 To 5
            If StrComp(city, CStr(labels(g)), vbTextCompare) = 0 Then Exit For
        Next g
        If g > 5 Then GoTo UnknownCity

        For colNo = 1 To 9
            groups(g, nextRow(g), colNo) = data(rowNo, colNo)
        Next colNo
        nextRow(g) = nextRow(g) + 1
    Next rowNo

    For g = 0 To 5
        For rowNo = 1 To 11
            For colNo = 1 To 9
                block(rowNo, colNo) = groups(g, rowNo, colNo)
            Next colNo
        Next rowNo
        targets(g).Range("A1:I11").Value2 = block
        targets(g).Range("B2:B11").NumberFormat = "dd-mm-yyyy"
        targets(g).Range("G2:G11").NumberFormat = "#,##0.00"
    Next g
    Exit Sub

UnknownCity:
    MsgBox "Review the city on Orders row " & rowNo
End Sub

Read the plan in three stages. First the code resolves each known target and gives it the source headers. Second it reads each source city, finds the matching approved group index and stages that complete row in memory. Third it copies each group into a two-dimensional block and writes it to that group's sheet. Blank entries in the reserved area replace any earlier results left below the current group. This is deliberate snapshot replacement. Do not place other work inside those rectangles.

There are three dimensions in the temporary plan: group, row and column. The two-dimensional buffer is still needed for a worksheet write. This uses the same row-relative concept as copying one rectangle. A grouped row retains its original raw city text. The clean city is used only for routing, so it does not prevent the combined check from comparing the raw fields against the original.

Check one wrong group and one known batch

  1. Run SplitByCity. Read Pune's four IDs and amounts 64, 110, 150 and 220. Verify the sum of 544. Read Nashik's two IDs with 270 and 90 and a sum of 360. Read one of the four single-row groups, such as Solapur with 1299.
  2. Verify the other three groups separately: Nagpur holds 240, Kolhapur holds 232 and Sambhaji Nagar holds 195. Add the six subtotals; they should equal 2,870. Exclude the header and unused rows from the counts. The header is repeated once in each output by design.
  3. In a separate test copy change Orders C2 to an unknown label. Re-run SplitByCity. It should identify row two and stop before rewriting the output ranges. Any earlier group view is stale while the source differs. Restore the original city and rerun to obtain current snapshots.

Reconcile the city exports before publishing CombinedReview

Public Sub CombineCitySheets()
    Dim original As Variant, names As Variant, labels As Variant
    Dim part As Variant, result(1 To 11, 1 To 9) As Variant
    Dim seen(2 To 11) As Boolean
    Dim area As Worksheet, summary As Worksheet
    Dim groupNo As Long, rowNo As Long, colNo As Long
    Dim sourceRow As Long, outputRow As Long
    Dim key As String

    If Not LoadPracticeOrders(original) Then
        MsgBox "Check the fixed Orders practice layout."
        Exit Sub
    End If

    Set summary = ThisWorkbook.Worksheets("CombinedReview")
    If summary.ProtectContents Then
        MsgBox "Use the prepared CombinedReview practice sheet."
        Exit Sub
    End If

    names = CitySheets()
    labels = CityLabels()
    For colNo = 1 To 9
        result(1, colNo) = original(1, colNo)
    Next colNo

    outputRow = 2
    For groupNo = 0 To 5
        Set area = ThisWorkbook.Worksheets(CStr(names(groupNo)))
        part = area.Range("A1:I11").Value2
        For colNo = 1 To 9
            If VarType(part(1, colNo)) <> vbString Then GoTo ReviewSnapshot
            If part(1, colNo) <> original(1, colNo) Then GoTo ReviewSnapshot
        Next colNo

        For rowNo = 2 To 11
            If Not IsEmpty(part(rowNo, 1)) Then
                If VarType(part(rowNo, 1)) <> vbString Then GoTo ReviewSnapshot
                key = CStr(part(rowNo, 1))

                For sourceRow = 2 To 11
                    If original(sourceRow, 1) = key Then Exit For
                Next sourceRow
                If sourceRow > 11 Then GoTo ReviewSnapshot
                If seen(sourceRow) Then GoTo ReviewSnapshot

                If VarType(original(sourceRow, 3)) <> vbString Then GoTo ReviewSnapshot
                If StrComp(CleanPracticeCity(CStr(original(sourceRow, 3))), _
                           CStr(labels(groupNo)), vbTextCompare) <> 0 Then GoTo ReviewSnapshot

                For colNo = 1 To 9
                    If IsError(part(rowNo, colNo)) Then GoTo ReviewSnapshot
                    If VarType(part(rowNo, colNo)) <> VarType(original(sourceRow, colNo)) Then _
                        GoTo ReviewSnapshot
                    If part(rowNo, colNo) <> original(sourceRow, colNo) Then GoTo ReviewSnapshot
                    result(outputRow, colNo) = part(rowNo, colNo)
                Next colNo
                seen(sourceRow) = True
                outputRow = outputRow + 1
            Else
                For colNo = 2 To 9
                    If Not IsEmpty(part(rowNo, colNo)) Then GoTo ReviewSnapshot
                Next colNo
            End If
        Next rowNo
    Next groupNo

    If outputRow <> 12 Then GoTo ReviewSnapshot
    summary.Range("A1:I11").Value2 = result
    summary.Range("B2:B11").NumberFormat = "dd-mm-yyyy"
    summary.Range("G2:G11").NumberFormat = "#,##0.00"
    MsgBox "Combined all ten original orders."
    Exit Sub

ReviewSnapshot:
    MsgBox "City data failed reconciliation. Rebuild and review the saved snapshots."
End Sub

For each populated key, find the original record and test its membership and values. Mark the original row as seen when a copied record passes. A repeated key can no longer consume another free output slot. Since there can be at most ten distinct matching original IDs, the staged block stays inside its declared range. A final position of twelve means ten rows were placed after the header. The combined output is grouped by the order of the six named sheets, so it need not match the original worksheet order. Use the ID, rather than row position, when checking both sources.

The short GoTo branches jump to the validation message and skip the final write. They are used for deliberate worksheet-data checks and do not handle a missing target sheet or other runtime error. If an expected worksheet does not exist, stop in the practice copy and create the exact required tab before trying again. The error handling lesson explains how to report runtime failures without hiding them.

  1. Run CombineCitySheets after all six output checks pass. Count ten data rows and compute the sum of the CombinedReview amounts independently. Expect 2,870 and the full input ID set. Check that Notes and the source are still present.
  2. In the duplicate test copy copy one city row on top of another used row, leaving the sheet total number of records the same. The seen-ID check should reject it. Previously combined data remains in place. Do not treat it as a successful new run. Rebuild the snapshots to restore the original set.
  3. In a practice copy change the amount in just one snapshot row. An order with the same key then has a different value. The combined check should reject before the output range changes. Rebuild the snapshots and repeat both aggregate and ID checks before ending the lab.

Read the records behind the reconciliation

Write the expected city subtotals independently

Test the full set of six practice snapshots
WorksheetRowsAmount
City_Pune4544
City_Nashik2360
City_Nagpur1240
City_Kolhapur1232
City_Solapur11299
City_SambhajiNagar1195

The sum is 544 + 360 + 240 + 232 + 1,299 + 195, which is 2,870. The group sizes add to ten. At first glance the single Solapur row contributes a large share of the amount. This is expected because the original BLK-1007 has 1,299. The arithmetic is distinct from whether returns or cancellations are recognized as revenue. This exercise copies all original records and uses the amount field as recorded. A separate calculation limited to Delivered would give a different result.

Use worksheet formulas outside the reserved output ranges. In the combined sheet, A2:A11 contains the ten ID results and G2:G11 the copied amounts. In each city sheet G2:G11 contains some amount values and truly unused rows beneath them. With the known numeric fixture, COUNT identifies how many copied amounts are present and SUM adds them. Compare them with the six expected totals and with the source.

=COUNTA(A2:A11)
=COUNT(G2:G11)
=SUM(G2:G11)

Explain a result even when a bad group keeps the same amount

Two types of mistakes can produce plausible sums. Moving a record to the wrong city can keep the overall sum and count unchanged. Splitting by a badly normalized label can instead place a record in an unexpected group. In the first case the validation compares the original row's normalized city with the allowed city for that tab. Try moving a complete Pune row to an extra available slot in Nashik in a scratch copy, then clearing the nine copied fields from its original group slot. A total count check may still pass. The membership check rejects the mismatched group.

In the second case, the input city might contain a nonbreaking space between the two words. The Trim helper deliberately converts Unicode 160 to an ordinary space and collapses repeated spaces. It does not turn unknown spellings into known labels. If the export has a new city, a real report owner should approve the spelling, output sheet and grouping change. The practice macro instead reports the exact source row so an operator can investigate before writing any new groups.

A duplicate ID can take the place of another at the same count, so trace the candidate key to the exact source before adding it. Adding a 64-rupee order twice and omitting an unrelated 64-rupee order could even make both gross totals agree. Keep the set of original and seen IDs alongside your aggregates. A moment spent choosing a reliable key makes the check stronger than inspecting a second copy of the same total formula.

Read an order snapshot one row at a time

For Pune the expected sequence in the named output is BLK-1001, AMN-1003, BLK-1006 and BLK-1009. It follows their source order. The combined order begins with these four Pune rows, followed by the two Nashik rows and the other city groups. That is a deliberately different sort from the source. Compare records by key. If another process requires the original order, preserve a source index and add a tested sort later. The current reconciliation checks content independently of row position, which is exactly what regrouping changes.

Consider the first two rows in the combined output. They both belong to Pune and their amounts are 64 and 110. The second includes a different storefront label because it was copied from the exact AMN-1003 source record. A naive routine that copied only the ID and City and then calculated new fields could accidentally associate the wrong amount or status after sorting. This lesson copies the nine fields together and compares them by original ID. Retain the fields a downstream reviewer actually uses.

Trace one Pune row and one rejected duplicate

  1. Read the source

    AMN-1003 has Pune, amount 110 and Delivered in its original record. The city lookup chooses only the allowed Pune group.

  2. Copy the whole row

    Place the original nine fields together on City_Pune. Verify the record appears once. The snapshot adds 110 to the Pune subtotal.

  3. Reconcile by key

    Combine finds AMN-1003 in Orders and checks the same group and field values. It records that the source position has been seen.

  4. Stop on a duplicate

    Another copy of the same key cannot pass. The final CombinedReview write is skipped, even when earlier combined cells remain populated.

Keep workbook changes visible when something fails

Differentiate user state and worksheet state

The practice macros do not need to select a cell, transfer from the clipboard, disable screen updates or change Excel's alert behavior. They work with qualified objects and narrow output ranges. A routine preparing a shared workbook may need additional behavior, such as selecting a view for a person or configuring conditional formatting. Give each behavior its own reason and evidence. Never rely on a suppressed warning to decide that an existing report is safe to replace.

In desktop Excel, worksheet protection and sheet names must match the prepared example. Output references are resolved before writing. If a city sheet is missing, the code can stop with a runtime error during its lookup. If a later target range is merged or otherwise unsuitable, an unexpected error could occur after some earlier city ranges were written. A sequence of writes across sheets is not an all-or-nothing operation. Keep the separate backup, compare all six outputs against the same source and rebuild from a known state before treating a partial run as complete.

FormatDailyReport has its own sequence of writes: the copied data block, the helper columns and formatting. A protected or unexpected layout can interrupt later operations. Verify the observed report instead of concluding that a failed test left all earlier cells untouched. The lesson's validation guards control expected fixture failures before writes. They do not substitute for a larger workbook's recovery policy or guarantee that nothing can fail during a write. Start with the planned blank ranges and existing markers.

List existing worksheets as a read-only diagnostic

If you are unsure whether all named tabs were created, this small inspection prints each worksheet name and its used area. It doesn't add names to the allowed input list. The UsedRange address is a description of the worksheet's current used area, which may include formatting. The code can help you spot an incorrect sheet name and leave grouping membership to the explicit arrays.

Public Sub ListAllSheets()
    Dim ws As Worksheet
    For Each ws In ThisWorkbook.Worksheets
        Debug.Print ws.Name, ws.UsedRange.Address
    Next ws
End Sub
  1. Run ListAllSheets in your own practice file. Find Orders, Report, CombinedReview, Notes and the expected six city tabs. A different workbook with a tab of the same name is unrelated to this project. The routine shows its own workbook's names only.
  2. Compare the group code's approved names with what the printout reports. A name that was abbreviated for display may still contain a different spelling in the actual tab. Fix the practice setup or deliberately change the allowed list and corresponding expected city together.
  3. Compare the displayed used area with the number of rows you expect. A used region can include formats even when some rows contain no order. Use the key and amount formulas for record evidence. Seeing J or K in a report's used area means those prepared columns exist, without saying that every row is valid.

Choose the recovery step from the failing stage

  • Source validation failure: Check the nine headings, ten IDs, amount types and A12 limit. An extra eleventh ID requires separating a new report contract from this exact fixture. Do not delete a legitimate new order just to reuse the old sample. For a real expansion use the last-row lesson and define the new report bounds.
  • Old snapshot visible after a failed combine: Observe whether the final success message appeared and read the affected stage. A validation failure leaves the previous combined range unchanged. Write down that its existing output belongs to an earlier source state. Recreate the snapshots from a verified input before combining again.
  • Wrong expected total: Check the underlying record IDs, input amount types and grouping rule. All original source rows are included in this split. The Delivered total is deliberately a different business question and should be labeled separately. Use per-city row counts and sums before calculating a whole-workbook total.
  • Output range already used: Choose a new approved practice copy with empty reserved blocks. The write scopes in the examples have predeclared ownership. If another analyst records a note in those rectangles, their note would be replaced. Set aside a separate worksheet or put persistent notes beyond the practice area.

Make a useful handoff: Write down the workbook, original source scope, date of the last run, group count and result of the ID and amount comparisons. Say whether the old combined view is still current after a validation failure.

Teach the report view to show its evidence

Highlight the checked output instead of duplicating the rule

The source has late and on-time checks that depend on both status and minutes. The Report already has those decisions in its Timing column. On a disposable copy, a worksheet conditional formatting rule can use the prepared result directly. Select the report area A2:K11. Use the conditional formatting option that accepts a formula and set the condition below. Pick a light highlight with readable text, then verify the rule applies only to that selected rectangle. Excel for Mac and Windows can present the creation menus differently. Use the client's rule manager to check the range and returned effect.

=$K2="Late"

The dollar sign fixes the column at K and lets the row number adapt across the selected area. That means the first data row uses the check in K2. The last row uses K11. Expect rows six, eight and eleven to highlight. The decision is based on the previously prepared tag, so after editing raw data you need to rebuild Report before treating the highlight as current. For the exact example, a cancelled row keeps its own status in the source and receives Timing not applicable in Report, so it remains outside the highlighted set. Confirm this in addition to checking the three late rows.

Separate a visual choice from the data contract

Freeze the top row if you want the labels to remain on screen during a scroll in your client. This is a view choice. An analyst can make that choice independently of rebuilding the numeric column formats in a real report. The example uses a neutral decimal display for rupees and preserves the underlying numeric amounts. Give the worksheet a clear unit label beside the report and compare a numeric sum. Avoid treating a number formatted with a different unit as a currency conversion.

If you later need the macro to prepare a consistent on-screen view, write a short checklist for the relevant workbook window. Opening another window or another workbook can change the current selection. Qualification of the ranges protects the stored data and formatting writes. A window setting belongs to a displayed window and needs its own context check. Keeping the freeze action out of this lab allows you to verify the macros from Notes without switching the view.

Make a missing-key case visible

In a test copy after the split, clear just the ID in a populated city row. Leave its amount and labels in the same places. That row now fails two ordinary assumptions: it is not an unused blank row and it has no key linking it to Orders. The combined reader checks other fields when the key is missing. It can reject the row before any final write. Simply skipping every blank ID could hide a partial paste or a damaged snapshot.

For contrast, a completely empty slot below the last row of a small city group is expected. It can remain inside the reserved rectangle while the group contains one valid order. Keep these cases different in your support notes. A slot outside the current data may be empty after the latest rebuild. An incomplete row has some fields populated and requires investigation. The sample's header and count checks can coexist with this per-row condition because they concern different boundaries.

When you restore the known state, rebuild from Orders instead of typing an ID you think was present. Use the original group's exact key list and Sum test to confirm the recovery.

Compare the measures with a tiny change

Suppose the old quote at BLK-1001 changes from 64 to 70 in the authorized practice source. The gross sum becomes 2,876 and the Pune subtotal becomes 550. Existing city snapshots still store the older 64. The reconciliation can reject their mismatch even if their own combined amount would independently match the prior total. Rebuild the city groups first, then retry the combine. FormatDailyReport can be rerun independently so its snapshot also reflects 70. No script is designed to update unlocked data automatically in a different file.

Test the result with the source field and original key. The row still has nine minutes and Delivered, so the timing label On time remains the same. The two outputs answer different questions. Recording exact changed and unchanged values makes your verification understandable to the analyst who will read the next report without the editor open.

Quick checks

Compare the three stages and their results

What changes when the amount 64 is formatted as 64.00?

The report's number format changes its display. The numeric value remains 64 and contributes to the sum of 2,870. The source value and its ownership are separate checks. Read the amount in the formula bar or compare the independent SUM of the source and report.

Which three report rows qualify for Late in the original data?

Rows six, eight and eleven are Delivered and have elapsed times 16, 18 and 17. The report uses a threshold strictly above 15 minutes. Cancelled or returned records, even with a recorded time, receive a different label for this summary.

Why keep a raw city and a clean city in the report?

The raw value helps explain what came from the source. The clean value makes known groups consistent after converting the nonbreaking space and reducing ordinary spaces. A reviewer can see which change was a preparation step. The report write does not have to overwrite the source.

What should happen if one city is unknown when splitting?

The practice procedure reports its source row and exits before it writes the six groups. Old group snapshots can remain and belong to an earlier run. Confirm the city label and permitted output before rebuilding. Unknown inputs should not silently be dropped while declaring the split complete.

Why can ten combined rows still fail reconciliation?

One of the records may be duplicated, missing from its correct city or changed after the split. Count alone cannot establish identity or field equality. The combined procedure tests each key against Orders and records which source positions have already been used before writing the finalized range.

What changes when BLK-1001 rises from 64 to 70?

The source gross and Pune subtotal rise by six, to 2,876 and 550. The old city extract still holds 64, so running Combine against the changed source should fail until snapshots are rebuilt. The elapsed time and status are unchanged, so its existing timing decision still agrees with those fields.

Interview and discussion

Explain why each workbook effect is limited

Where would you validate data when a macro writes to multiple sheets?

Check shape, expected headers, IDs, numeric fields and intended destinations before the first write. Prepare each snapshot's values in memory. Make a separate safeguard for failures that occur after a write begins, because sequential sheet edits are not a transaction. In the practice version verify all six sheets against the same source after the run.

Why not combine every sheet except Orders?

Another sheet might be a note, another report or a worksheet with the wrong schema. Use an explicit set of known outputs with expected city labels and exact headers. The diagnostic listing of all worksheets helps a developer find an intended tab but should not silently become the list of inputs.

How do you prove that copied data still has its original relationships?

Use the unique record ID to find the entire original row. Compare the nine fields, including amount, city and status, under the same rules. Verify every known ID occurs once and each belongs to the approved group. Compare gross sums afterward as an independent arithmetic check.

What do you do with an old combined view after the new source fails validation?

Keep its provenance visible in your run notes. Its previous data may still be present, but the new source was not successfully reconciled. Repair the practice input or regenerate the correct city snapshots from the newly validated Orders set, then verify the final output by ID and total.

How could you generalize this ten-row example without losing safety?

Define how a current record is identified and choose a dependable boundary such as a validated Table. Determine the new output sizes and which writer owns each range. Preserve complete records and explicit input sheet choices. Re-test with zero rows, many groups, invalid labels, a duplicate ID and an older snapshot before use on a real approved workbook.

Six recall cards

  • Preserve source

    Read Orders and write the prepared Report. New styles, clean city and timing belong to the report range.

  • Use named groups

    Resolve the six approved practice sheets. Copy only the rows that belong to each matched city.

  • Do the arithmetic

    Pune has four records and 544. Nashik has two and 360. All six groups add to ten and 2,870.

  • Reconcile by key

    One duplicate and one omission can hide behind a correct count. Verify original fields and group membership for every key.

  • Keep the write bounded

    The practice uses named existing sheets and reserved ranges. No existing sheet needs to be deleted to rebuild a snapshot.

  • Check freshness

    An old combined output can survive a failed validation. Compare its data and run status before relying on it.

Microsoft references

Continue practising: explore the existing Excel Task Hub for additional exercises.