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

12. Macros and VBA

Excel

12.14 Error Handling with On Error

Priya runs a city summary and gets a message that the Orders sheet cannot be found. The old report is still visible. She needs to know whether a new result was written and whether Excel returned to its earlier settings. You will handle a missing worksheet, guard against a zero denominator and test a small cleanup path.

Give each failure an appropriate response

Separate routine validation from an unexpected failure

CityBasket is fictional. The practice order list resembles a Blinkit-style delivery report, with invented orders and workflow. In the original ten records, Pune has four gross order amounts of 64, 110, 150 and 220. The sum is 544 and the average is 136. The report may also be asked for a city with zero matches. That is an ordinary result in a grouped report. If the sheet itself was renamed, the code could fail before it obtains the input at all.

  • Expected validation result: A missing city choice, invalid amount or no matching orders can be handled with an ordinary If check and a clear return. A divide-by-zero error is unnecessary if you first test whether the order count is positive.
  • Runtime error: Excel or VBA can report a failure while an instruction is executing. A worksheet name that cannot be resolved in the selected workbook is one example. An error handler can capture its number, description and the operation you attempted.
  • Compile issue: A malformed statement or undeclared name can be detected before execution. An On Error handler for a running procedure will not fix that source error. Use the editor's code diagnostics to correct it and verify the small test again.
  • Wrong result without an error: A report can successfully use the wrong city or ignore a cancelled record. Compare the output and its count with independent data. A handler that was never called does not prove that the calculation adopted the right policy.
Attempt to locate Orders, save error details and stage if the lookup fails, and check that the previous output still remains.
Find out where the run stopped and what effects had already occurred. Handle an expected missing group without triggering an exception.

State the intended outcome before adding a handler

The report needs three values: count, gross recorded amount and average. For a matching group all three can be prepared in memory and placed into a small output range after validation. For a city absent from the practice data, return a clear message and preserve the earlier output. It belongs to a different run. For a missing worksheet, report the stage where retrieval failed. A time-stamped note or explicit current marker can help an operator avoid reading a previous number as today's outcome.

Remember: Guard ordinary choices and invalid values through normal control flow. Use a runtime handler to preserve information about an instruction that could not complete.

Read what On Error controls

Keep the starting mode and end of the handler visible

Use these statements for deliberately different paths
StatementEffect
On Error GoTo FailedEnable a handler at a label inside this procedure
On Error Resume NextContinue after a failing statement in its handled scope, where appropriate
On Error GoTo 0Disable the enabled handler in this procedure
Err.Number and Err.DescriptionRead information about the most recent failure
Resume CleanupLeave the active handler and continue at the named label

A label is a named position on a line in a procedure. Put the cleanup or failure labels in the same procedure that uses them. On a normal path, exit before the code for a failure. A run can reach a label through ordinary sequencing if you omit that exit. Put your success and failure observations into separate branches so the developer can tell which one ran.

VBA distinguishes an enabled handler from one that is already active because it is handling an error. If another error occurs inside an active handler, VBA may look outward for a suitable caller's handler. Save the original Err information at the start of the handler. Then perform cleanup at an appropriate exit path. Logging calls and further failures can overwrite the error information. Store the source, description and intended stage you will need to diagnose the run.

Use narrow continuation for a known check

On Error Resume Next can be useful when you intentionally try one operation whose failure you inspect immediately. Leaving it active over a series of writes can conceal incomplete effects. A common safe teaching pattern is to use it in a short helper or a carefully scoped cleanup action, read Err right away and turn the mode off. The caller can then decide how to report that failure. This policy helps avoid excited success messages after an earlier write was skipped.

Lab one. Publish a city result only after validation

Prepare a known input and a clearly marked earlier result

Make ErrorPractice.xlsm in approved desktop Excel and put the ten order values from the formulas chapter on its Orders sheet. Use the original cities in C2:C11 and numeric gross amounts in G2:G11. Make a Report sheet. B2 is the city request. In Report E2 through E4 make space for order count, total and average. Put their labels in D2 through D4. Place a separate note in G2 that should stay still during the tests.

Check each city against the same ten original rows
Requested cityCountTotalAverage
Pune4544136
Nashik2360180
Mumbai0No new reportNo new report

The procedure writes the result only after reading and validating the needed values. A different city result, a missing sheet or an unhealthy source value each has its own message. This fixed-size practice version does not rely on implicit worksheet selection. Use a standard module that belongs to the ErrorPractice file.

Option Explicit

Public Sub SafeCityReport()
    Dim ws As Worksheet, report As Worksheet
    Dim wanted As Variant, rawCity As Variant, amount As Variant
    Dim city As String, stage As String
    Dim rowNo As Long, orders As Long, total As Double
    Dim answer(1 To 3, 1 To 1) As Variant
    Dim errorNumber As Long, errorText As String

    On Error GoTo Failed

    stage = "Find Orders"
    Set ws = ThisWorkbook.Worksheets("Orders")
    stage = "Find Report"
    Set report = ThisWorkbook.Worksheets("Report")
    stage = "Read selected city"
    wanted = report.Range("B2").Value2

    If VarType(wanted) <> vbString Then
        MsgBox "Enter a city in Report B2."
        Exit Sub
    End If
    city = Trim$(CStr(wanted))
    If Len(city) = 0 Then
        MsgBox "Enter a city in Report B2."
        Exit Sub
    End If

    For rowNo = 2 To 11
        stage = "Read Orders row " & rowNo
        rawCity = ws.Cells(rowNo, 3).Value2
        If VarType(rawCity) <> vbString Then
            MsgBox "Review the city in Orders row " & rowNo
            Exit Sub
        End If
        If StrComp(Trim$(CStr(rawCity)), city, vbTextCompare) = 0 Then
            amount = ws.Cells(rowNo, 7).Value2
            If VarType(amount) <> vbDouble Then
                MsgBox "Review the amount in Orders row " & rowNo
                Exit Sub
            End If
            orders = orders + 1
            total = total + amount
        End If
    Next rowNo

    If orders = 0 Then
        MsgBox "No matching orders for " & city
        Exit Sub
    End If

    answer(1, 1) = orders
    answer(2, 1) = total
    answer(3, 1) = total / orders
    stage = "Write Report E2:E4"
    report.Range("E2:E4").Value2 = answer
    Exit Sub

Failed:
    errorNumber = Err.Number
    errorText = Err.Description
    MsgBox stage & " failed. Error " & errorNumber & ": " & errorText, _
           vbExclamation, "Safe City Report"
End Sub
  • Capture the operation you are about to attempt. Change stage before the worksheet lookup, read or write. If something fails, you can report what was attempted independently of the description supplied by VBA.
  • Reject unusable data without relying on an error. A blank city or nonnumeric amount has a known review path. Treat a genuinely absent group as a normal no-match result. There is nothing useful to divide when the order count is zero.
  • Collect the three outputs as one small result. The array records count, total and average only after there is a valid group. The procedure then assigns the matching three-cell range. Check which stage failed before treating the old output as a new response.
  • Keep failure handling focused. The final handler immediately saves the number and description and gives the operation to the reader. It never declares success or resumes the failed statement. This Sub does not change shared application settings, so there is no app state to restore here.

Exercise four results and read their evidence

  1. Enter Pune in Report B2 and run the procedure. Expect 4, 544 and 136. Calculate all three independently from the four visible source rows. The data label covers all statuses. Check the note in G2.
  2. Change B2 to Mumbai. The no-match message should appear. E2:E4 can still show your previous Pune result. Record its previous run and do not label it Mumbai. This early return is an expected case rather than a runtime error.
  3. In the disposable copy temporarily rename Orders to OrdersPracticeHold. Run again. The handler should report that finding Orders failed. This lookup commonly raises VBA error 9 for the missing member of the collection. The phrasing of its description can vary. Neither the earlier output nor the note should change.
  4. Restore the name, enter Nashik and run. Expect E2 through E4 to change to 2, 360 and 180. If the debugger stops at the failing statement before the handler in the earlier test, inspect its error trapping option or use the predicted trace. Do not change organization policy just for the exercise.
  5. In an isolated copy make one matching amount a text value. A row-specific validation message should appear, with no accepted new output. Restore the numeric fixture to finish. If you can only reason about the code, follow stage and answer through each source change and identify whether the final assignment is reached.

Lab two. Restore an application setting after a controlled failure

Keep the demonstration in a known, isolated practice session

Some desktop macros temporarily turn off screen updating, which controls how Excel redraws its windows while work occurs. Application settings belong to the running Excel instance. This lesson's small reports can work without changing that property. The following separate demonstration shows how to restore the value if a larger approved routine does need to change it. Do this exercise only in your own training session or trace it from the code.

An original True or False screen updating setting should be restored to its exact saved value after both success and a controlled failure.
Restore what was present on entry. A caller may already have changed the setting before this procedure starts.
Public Sub TestCleanupNormal()
    RunCleanupDemo False
End Sub

Public Sub TestCleanupFailure()
    RunCleanupDemo True
End Sub

Private Sub RunCleanupDemo(ByVal simulateFailure As Boolean)
    Dim previous As Boolean, captured As Boolean
    Dim stage As String, failureStage As String
    Dim originalError As Long, originalText As String
    Dim restoreError As Long, restoreText As String

    On Error GoTo Failed
    stage = "Capture display state"
    previous = Application.ScreenUpdating
    captured = True

    stage = "Run controlled demonstration"
    Application.ScreenUpdating = False
    If simulateFailure Then
        Err.Raise vbObjectError + 2048, "RunCleanupDemo", _
                  "Training failure before any worksheet write."
    End If

Cleanup:
    If captured Then
        On Error Resume Next
        Err.Clear
        Application.ScreenUpdating = previous
        restoreError = Err.Number
        restoreText = Err.Description
        On Error GoTo 0
    End If

    If originalError <> 0 Then
        Debug.Print "Failed at", failureStage, originalError, originalText
    Else
        Debug.Print "Demonstration finished."
    End If

    If restoreError <> 0 Then
        Debug.Print "State restoration failed.", restoreError, restoreText
    ElseIf captured Then
        Debug.Print "Before / after", previous, Application.ScreenUpdating
    End If
    Exit Sub

Failed:
    originalError = Err.Number
    originalText = Err.Description
    failureStage = stage
    Resume Cleanup
End Sub
  • Capture before changing the setting. Read ScreenUpdating and set a flag once the original value is available. If capturing the value itself fails, the cleanup does not assume a prior True or False. Both test entry points share the same procedure.
  • Create a reproducible failure. The training failure uses Err.Raise with an application-defined error number and a message you can recognize. It does not alter a worksheet or file. The branch is deliberately activated only for TestCleanupFailure.
  • Save the error before restoring state. The active handler reads the original error number, text and stage, then uses Resume Cleanup to move to the known label. This is different from repeating the instruction that raised the deliberately generated error. The routine can now report the original problem regardless of its next cleanup result.
  • Check one restoration action. Inside Cleanup, the narrow continuation mode protects the recovery attempt so the next lines can record Err details if setting the property failed. Clear old error information immediately before the attempt. Turn off the local mode as soon as those details are read.
  • Keep separate failure messages. A successful operation with a restoration problem is still incomplete. The code prints both the operation outcome and any restoration failure. It does not claim “restored” when it cannot observe the intended setting. Read the final Before / after line only on the successful restore path.

Verify the end states without leaving Excel in a changed mode

  1. Paste these routines below the city routine in the same practice standard module. Inspect them and use the Macros dialog scoped to your exercise. Run TestCleanupNormal. In the editor's Immediate window expect a finished message and matching Boolean before and after values.
  2. Run TestCleanupFailure. Expect the controlled training failure string with the stage Run controlled demonstration, followed by matching before and after settings. No worksheet cell changes. If the debugger is configured to break for all errors, manually use the planned trace instead of disturbing another workbook or changing shared settings for this test.
  3. Compare the observed setting with the previous value. If it was True the expected restored value is True. If this routine is called by a parent macro already holding the setting False, its local cleanup restores False. Do not manually leave the setting changed between your tests. You can trace the False case on paper.
  4. If a restoration message appears, distinguish it from the original failure report. Return to an approved clean desktop session before testing another routine. A stop, forced reset or external crash can bypass VBA cleanup. The exercise covers normal completion and a handled VBA failure within the running procedure.

Trace the deliberately raised error

  1. Capture the starting state

    Record the existing ScreenUpdating value before changing it. The cleanup flag now says this value is known.

  2. Run the failure branch

    The test raises a named training failure. VBA transfers control to the enabled handler.

  3. Preserve the diagnostic

    Save the stage, number and description in local variables. Resume at the cleanup label.

  4. Restore and report

    Put the saved setting back. Report the failure and separately verify whether restoration was successful.

Plan the handling with small before-and-after checks

Choose what should stay intact if the run fails

In the city example the output write is a single block after validation. A missing Orders sheet fails before the code reaches the Report write. A missing or invalid group is also caught earlier. For a larger procedure with multiple writes, an error can occur after the first sheet has changed. A handler that restores ScreenUpdating will not restore all the worksheet values. Give the user an approved recovery plan and read the actual output around the failure, especially before retrying any action that could append data twice.

One useful pattern is to stage as many row decisions as possible in memory, then write a bounded block once a complete batch is known. This reduces the number of partial worksheet states you have to handle. It does not guarantee transaction behavior. A write can still fail because a destination is protected or its shape does not match. A completed first region can still remain after a subsequent error. Test how stale and partial results will be recognized.

Do not use errors to limit ordinary calculations

When there are zero matching orders, both the total and count might be zero. The average of no rows is undefined. The report intentionally exits before dividing. The exact runtime number a malformed expression would produce is unnecessary information for deciding a known no-match case. Use the count guard, show a clear message and avoid a misleading average of zero. A group with two records worth zero is a different valid case: count two, total zero and average zero.

For a numerical overflow, examine both the target variable and intermediate expression. A larger destination variable cannot always repair an overflow that happened before assignment. The chapter's variable lesson gives simple types and ranges for that reason. Use predictable limits for real input rather than waiting for VBA to decide whether every arithmetic expression fits.

Try one narrowly scoped optional operation

Make an expected missing worksheet a visible outcome

Suppose someone keeps an optional Archive worksheet in older versions of the training workbook. It is fine if a new practice workbook has no such sheet. A learner asks whether On Error Resume Next can help check it without putting the whole workbook action into that mode. The source of the expected failure is one lookup. After that lookup there is enough information to decide whether the sheet was absent, whether it was found or whether a different failure needs investigation.

Public Sub ProbeOptionalArchive()
    Dim archive As Worksheet
    Dim lookupError As Long, lookupText As String

    On Error Resume Next
    Err.Clear
    Set archive = ThisWorkbook.Worksheets("Archive")
    lookupError = Err.Number
    lookupText = Err.Description
    On Error GoTo 0

    If lookupError = 9 Then
        Debug.Print "Archive is absent in this practice workbook."
    ElseIf lookupError <> 0 Then
        Debug.Print "Archive lookup failed.", lookupError, lookupText
    ElseIf archive Is Nothing Then
        Debug.Print "No usable worksheet reference was returned."
    Else
        Debug.Print "Archive present:", archive.Name
    End If
End Sub

These statements inspect and report. They do not create an archive automatically or silently ignore the outcome. Run the procedure in your own copy with no Archive sheet and expect the absence message. Add a blank tab named Archive only in the disposable workbook and rerun. Expect the present message and check that the existing Report cells have the same data. If a different error is reported, retain the original description with the file name before making any setup changes.

You can also enumerate ThisWorkbook.Worksheets and compare their names. That can avoid depending on the collection lookup error for a known optional case. Choose the method that is easiest to read and test. In a short handler lesson it is useful to see an intentionally limited continuation scope. In production a branch that can perform the check without triggering an error may be simpler. In either approach, separate absence from a failure that should be surfaced.

Know the risk of leaving the line in the wrong place

Imagine the programmer moves On Error GoTo 0 below twenty lines of unrelated workbook code. A failing output lookup, an unsuccessful value write or a formatting operation could now fail and execution would continue. If a success prompt still appears at the end, the user could rely on an incomplete report. Keeping the mode next to its one intended operation makes this easy to audit. Store and test the local outcome immediately, then return to the appropriate normal handling.

Err.Clear clears the stored properties, while On Error GoTo 0 controls the scope's enabled handler. Clearing the Err object does not disable continuation behavior. In both examples the code clears the stored details immediately before the one recovery action and reads them immediately after. Moving another code call between those points can make the subsequent diagnostic describe the wrong failure.

Compare a good run, expected skip and actual failure

Record the observable differences

Begin with the verified Pune report unless a row says otherwise
ActionEvidenceResult cells
Run for NashikSuccessful write2, 360, 180
Run for absent MumbaiNo matching ordersEarlier 4, 544, 136
Run with Orders renamedFind Orders failedEarlier 4, 544, 136
Run with one Pune amount as textReview named source rowEarlier 4, 544, 136

Three rows share the same visible earlier result. The expected outcomes differ because the program took different paths. A careful acceptance test reads the message or stage and verifies that the write actually happened only for a valid group. The worksheet alone cannot tell why an older result stayed. To help the report user, pair it with the actual run information rather than copying its cells into a new report label.

There is no generic recovery from every error. If the source worksheet was deliberately renamed in the practice copy, restore its original name and rerun. If it was renamed as a legitimate template update, adapt the named lookup after discussing the changed contract and reviewing any other routines that rely on it. If the output range is reserved but protected, get the approved reporting copy or work with its owner. A handler should describe the issue without attempting to bypass security settings or overwrite somebody else's workbook.

Trace two diagnostics in one handled cleanup path

Read the order in RunCleanupDemo again. When it raises its named failure, the handler stores the original text before entering Cleanup. If restoring the app setting succeeds, that text is still available to print. If restoration fails, a separate variable records the later error. Label and retain both. A support person can then see which error interrupted the work and which operation failed while trying to return to the original state.

Consider a parent routine that had already set ScreenUpdating to False for its own reason. If your helper unconditionally set it to True on exit, it would undo the parent's intention. Saving the original Boolean lets the helper follow the known contract. The parent routine still owns its own eventual restoration. This principle becomes more important when a procedure touches several application-wide settings. Preserve each one before changing it, and restore only the values you actually captured.

Distinguish Resume and Retry

A plain Resume from a handler can retry the statement that failed. That may be appropriate only when the reason for failure has been fixed and running the statement again is safe. In our deliberate error example retrying would just raise the same error again. Resume Cleanup instead directs the code to a known conclusion and gives a useful diagnostic. If the user corrects the worksheet configuration, they can deliberately start a fresh operation and verify that it can handle the same input without duplicates.

When a procedure has already appended a row before another step fails, an immediate full rerun may append that row again. Before building an automated retry, use an independent report marker or record key to recognize a completed write attempt. The proper fix may be to replace a known report area or to review a partially completed batch. This lesson uses a bounded replacement. Even so, inspect the exact preserved results after a failure before treating those results as current.

Keep the handoff usable for someone who never saw the editor

  • Identify the execution: Record the workbook name, procedure, input group and time. The copied practice sheet's values may be different from another learner's. Give a reproducible smallest case with five or ten known records and one trigger.
  • State the stage: Say whether the failure happened during lookup, validation or the output. Add the actual number and description if VBA reported them. An ordinary missing-data branch can instead report which source row was rejected.
  • Describe the effect: Read the destination and decide whether earlier values remain, the new ones were written, or the state is partially updated. Verify app settings separately if your code changed them. A restored display doesn't establish the source data is safe or current.
  • Repeat only an approved action: Fix the expected training copy and rerun with identifiable values. Compare both a known success and one controlled failure. That gives you a clear observation of what the revised handler preserves.

Trace the state: Draw a line for the original runtime error and a separate one for the cleanup attempt. Explain how they can both occur and why a past result on the worksheet does not identify either diagnostic by itself.

Build a repeatable incident drill from a copied workbook

Visit each failure location in isolation

The city report encounters errors at different stages depending on which worksheet is missing. A useful learning fixture isolates the difference. Start with the successful Pune result and verify the earlier output. In the first disposable copy rename only Orders. The report object lookup has not run yet, and the previous Report remains available. In another copy keep Orders correct and rename only Report. The stage now changes to Find Report because the source lookup completed first. Neither path reaches the calculation. You can run both experiments only in a practice environment, or write them out.

After each test, keep a note about which lookup had finished. Use the named worksheet and exact workbook file when describing the issue. If both names resolve in your environment but a new result is not visible, inspect the next reported stage and the worksheet's cell ownership. Error 9 in the earlier test identifies a missing collection item but does not by itself prove which name failed. Two different worksheet lookups can get the same numerical error. The saved stage adds the context that makes the diagnosis useful.

Compare a protected destination with bad input data

Now trace another possibility without changing any native security setting. The procedure calculated four orders, total 544 and average 136. The destination sheet's expected cells are not writable under its installed state. The attempt is now at Write Report E2:E4. A desktop application can report a runtime object error here. Read the exact message and note that both named input sheets existed. You can inspect an approved prepared copy for the actual write scope. The proper remediation does not involve bypassing protection on an unrelated workbook.

Suppose instead a matching cell holds a formula result that is an Excel error. The code reads it into a Variant, checks the type and reports the row before attempting to add it to the total. This deliberately separates one known bad input from an instruction unexpectedly failing. The worksheet can contain an error result without throwing a VBA runtime exception at the moment you read Value2. Trying to use it as an amount before inspection could fail later. Give the reviewer the row and field rather than a generic error at the end of the run.

Trace the expected arithmetic in an alternative zero-valued example

If you create an alternate practice group with two accepted orders amounting to zero each, there are still two contributions. The exact expected result is count two, total zero and average zero. If the city has no rows, the count is zero and the procedure should skip the division and keep the previous result. The two cases demonstrate why an error handler alone is insufficient: a mathematical operation can be inappropriate due to the business input even before the program calls it. Model the two outcomes in your notes using the count and output write scopes.

Check a matching record with amount zero among otherwise positive amounts too. If AMN-1003's practice amount becomes zero while its city remains Pune, the sum drops from 544 to 434 and the count stays four. The resulting average is 108.5. If the amount is cleared instead, the flow reports the invalid row, makes no new write and does not publish 108.5. These numbers let a new learner prove that the guard checks a type rather than treating every result with a zero-like display as missing.

Use the step count after repairing the fixture

On a fresh, approved practice copy restore the original worksheet names and numeric amount. Start a deliberate run for Pune. Retain the original 4, 544 and 136 and confirm that the note in Report G2 stayed. Next execute the controlled cleanup demo while the app is in its normal state. The code prints the original value and the observed restored value, giving separate evidence from the worksheet result. Record those two observations as an incident drill outcome. A meaningful failure test also confirms the workflow can recover with its known good input.

When handing the example to another student, ask them to provide the earliest visible difference among the tests: the missing-group message, stage-specific runtime report or current numeric cells. This is a way to verify that they understood the distinction rather than simply memorizing the reported numbers. Include whether results were predicted from source or observed in the worksheet. Also record the selected city after each repair. The worksheet can keep the most recent valid calculation while the current request points elsewhere. Verify the number, the requested group and the presence of the original source before copying even a correct looking result to another report.

Quick checks

Predict the failure branch before running

What should the macro do for a city with zero matching rows?

Report the expected absence and return before attempting to divide. The output retains any earlier report. A result of zero average would suggest actual zero-valued orders were present, so report an empty group as its own outcome.

When does VBA enter the handler installed by On Error GoTo Failed?

During runtime a failed instruction can transfer control to the enabled label in the current procedure when that handler can handle it. Expected branches such as a missing city choice can return normally before any runtime error. A compile-time syntax error needs a source correction before the procedure runs.

Why put Exit Sub before the Failed label?

The label marks a position in the same routine. Without a normal exit or another explicitly chosen path, successful execution can continue straight into those lines. An ordinary exit separates completion from the code intended to read the error details.

What do you store before moving to cleanup?

Save the original error number, description and context such as the stage. If cleanup itself fails, it can affect Err. Storing the earlier values lets the support note distinguish the original failure from any failed restoration.

Should the helper always set ScreenUpdating to True when it finishes?

Restore the value held on entry. If the parent already had screen updates False, that is the expected end state for the helper. Attempt restoration on both normal and handled failure paths after correctly capturing the initial value. Inspect the actual before-and-after settings as a separate check.

What does On Error GoTo 0 do after a narrow Resume Next lookup?

It disables the enabled handler in the current procedure. It does not jump to a label named zero. Read and save the error information before switching the mode, then handle the specific documented outcome from that saved data.

Interview and discussion

Explain the expected result of a failed run

How would you avoid making a no-match result look successful?

Check the matched count before computing the average or writing a report. Show a clear no-match result for the requested city, and record that any visible worksheet cells belong to a prior run. A larger report can include a separate current status field so the reader can distinguish these states without relying on a message they might have missed.

Why keep runtime error handling separate from validation?

Validation expresses the business rules for cases that occur during normal use. A named-sheet lookup failure or protected write can require diagnostic details from Excel. Separate paths tell the caller which response is needed and make it possible to test both with a controlled fixture rather than hiding all problems behind one general message.

How do you test cleanup without relying on an uncontrolled real-world failure?

Use a separate training branch that explicitly raises an identifiable error after capturing the setting. In the run output verify the original stage and error description, then compare the before and after values. The test requires no workbook data changes. A separate normal branch should produce matching state without a failure report.

What guarantees does a cleanup handler give about an earlier cell write?

It performs the cleanup steps written by the procedure. Restoring a property or printing an error does not automatically roll back changes made before the failure. Inspect the result record and establish a recovery plan for every output scope. A report can stage a complete batch before writing to reduce but not eliminate partial-state concerns.

When is Resume Next reasonable in beginner code?

Use it for a short operation whose failure you intend to inspect immediately, such as probing an optional Archive sheet or restoring one captured property. Read and store the relevant error details, then disable that mode. Let the surrounding procedure decide what the failure means instead of continuing past a sequence of unverified writes.

Six recall cards

  • Guard ordinary choices

    A missing group is a known outcome. Check count before dividing and leave a clear report state.

  • Capture the stage

    Set a descriptive operation name before lookup, read or write. Retain the actual error number and description.

  • Normal exit

    Use an explicit exit before a failure label so successful execution does not flow into the handler.

  • Narrow continuation

    Use Resume Next around one checked recovery or lookup action, then turn its scope off.

  • Restore prior state

    Capture the original setting. Test both success and a planned VBA failure with the same cleanup path.

  • Check workbook effects

    Old values can survive an error. Inspect the write boundary and reload the report only after a verified successful run.

Microsoft references

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