12.10 Loops: For, For Each and Do
Rohan wants the total of every Pune order in a ten-row list. Reading each row once and carrying the amount forward gives 544. A VBA loop can make those repeated visits in order. You will trace the running total, iterate over a Range object and scan for the first missing order ID without going beyond a known boundary.
Write down what one visit to a row should do
Three possible rules for the same order sheet
A fictional Blinkit-style analyst needs morning figures from a small order list. The amounts and operations in this exercise are invented. The source grid has a city field, a gross amount and a status field. One question asks for the sum of all Pune rows. Another asks for the amount of every Delivered row, across all locations. A third checks where the IDs stop being consecutive. Those are different operations, even though each reads the same sheet.
- Iteration: One execution of the loop body is an iteration. In a row loop you can describe a visit as reading the current city, checking whether it is Pune and adding the row amount only when it matches. Check one visit by itself first.
- Counter: A counter indicates where the loop is. In a For loop named rowNo, it starts at the first row number and advances to the last with each Next. Use a Long value for Excel row numbers. A loop over row numbers is useful when you need to read several columns aligned in one row.
- Item: For Each sets its control variable to each item in a collection. The item may be one Range object identifying an amount cell. Read related information using the cell's row or a documented offset, then use the item itself for its amount.
- Condition: A Do loop can keep going while a condition is true or until a condition is true. Identify how the procedure advances toward that condition. If it visits a row position, increment the position and give it a safe bound. This improves both predictability and the ability to test errors.
- Accumulator: The running amount starts at zero and grows by one accepted value at a time. A counter for the matched rows can grow separately. Both are useful for checking the final sum. Another matching amount may be zero and still increase the count.
Read the first, middle and last step
In this practice row two is a data row, and row one has headings. A For loop starting at 2 therefore skips the header. A loop ending at 11 includes the last data row. Its count is ten because both endpoints are included. Since Pune matches four times, the loop still visits ten positions but only four contribute to the number you are measuring. Keep a small trace so a later report can distinguish a row missed by the loop from a row deliberately excluded.
The statement total = total + amount means read the old total, add the current amount and then update the stored value. Starting from zero, the first matching amount 64 gives 64. The next Pune amount is 110, so the total becomes 174. An intervening Nashik row can appear in the source list without changing the Pune amount. At the end, only the four matching amounts have changed the accumulator.
Remember: A loop needs a known beginning, a rule for each visit and a testable ending. Record how many rows it visited separately from how many matched.
Choose the repeat pattern before you type the body
Read each loop's boundary in the syntax
- For: The bounds give an initial counter and a final one. The default Step is one; Next advances the counter. When you specify a negative step, the starting point must be at the higher end to make the intended reverse visits. Do not change the counter independently in the loop body unless you deliberately design and test that behavior.
- For Each: The collection supplies each next object. In a contiguous amount range, each cell is a Range item. The cell's Range object can expose its address, current value and row. If you need a row number to write separate answers, either read that property or choose the counter version when numerically stepping between known rows.
- Do at the top: Do While a condition can skip the entire body if the condition is already false. Do Until tests the opposite sense. Keep the acceptable boundary visible beside the loop instead of hiding it in repeated worksheet operations.
- Do at the bottom: A condition written after Loop is checked after the body, so the body runs once even if the condition would otherwise prevent it. Use a top check for an empty-input situation if you expect the routine to do nothing when the first position is invalid.
- Exit For and Exit Do: These can stop the current loop early for a documented reason. A search for the first blank should end when it finds one. A total should report when it stops early on bad data, because the accumulated number then covers only part of its intended input.
A clear finish protects the data
Repetition can multiply a mistake too. First check a very small region in a disposable copy. If your routine writes a label, reserve an output column and confirm which rows need updating. If it deletes or moves data, redesign a non-destructive initial test that lists the intended changes. A loop over at most ten known records lets you step through the reason for every branch before you think about an entire range of exported orders.
Lab one. Follow each Pune amount through the loop
Place the source columns at their original addresses
Make your own LoopPractice.xlsm file and a tab named Orders. Reuse the original ten rows from the formulas chapter, or populate only the fields below. Order IDs belong in column A, City in C, Amount in G and Status in I. Keep the numbers numeric and labels as text. The initial IDs are populated from row two through row eleven. Put “Keep this note” in K2, outside the source. All three main routines on this page read data without writing any worksheet cells.
| Row | A ID | C City | G Amount | I Status |
|---|---|---|---|---|
| 2 | BLK-1001 | Pune | 64 | Delivered |
| 3 | BLK-1002 | Nashik | 270 | Delivered |
| 4 | AMN-1003 | Pune | 110 | Delivered |
| 5 | BLK-1004 | Nagpur | 240 | Cancelled |
| 6 | AMN-1005 | Kolhapur | 232 | Delivered |
| 7 | BLK-1006 | Pune | 150 | Delivered |
| 8 | BLK-1007 | Solapur | 1299 | Delivered |
| 9 | AMN-1008 | Sambhaji Nagar | 195 | Returned |
| 10 | BLK-1009 | Pune | 220 | Cancelled |
| 11 | BLK-1010 | Nashik | 90 | Delivered |
Type the code in one standard module in this workbook. Test only the project that holds your fixture. The routine requires a text city for all ten rows. When the city matches Pune, it also requires an actual numeric amount. For this small dataset, Trim removes ordinary spaces before a case-insensitive text comparison. The successful total includes Pune records of every status, so the cancelled amount of 220 is part of the result.
Option Explicit
Public Sub PuneTotal()
Dim ws As Worksheet
Dim rowNo As Long, matched As Long
Dim rawCity As Variant, rawAmount As Variant
Dim total As Double
Set ws = ThisWorkbook.Worksheets("Orders")
For rowNo = 2 To 11
rawCity = ws.Cells(rowNo, 3).Value2
If VarType(rawCity) <> vbString Then
MsgBox "Review the city at row " & rowNo
Exit Sub
End If
If StrComp(Trim$(CStr(rawCity)), "Pune", vbTextCompare) = 0 Then
rawAmount = ws.Cells(rowNo, 7).Value2
If VarType(rawAmount) <> vbDouble Then
MsgBox "Review the Pune amount at row " & rowNo
Exit Sub
End If
total = total + rawAmount
matched = matched + 1
Debug.Print rowNo, rawAmount, total
End If
Next rowNo
MsgBox matched & " Pune rows; total = " & total
End Sub
Trace the accumulator and compare a worksheet formula
- Before running, calculate 64 + 110 + 150 + 220 separately. Add the formula below in an unused cell for the same unmodified dataset. It computes the all-status Pune total. In the standard workbook fixture both arithmetic paths agree.
- Run PuneTotal through the Macros dialog in your practice workbook. Check for four matched rows and the total 544. In the editor's Immediate window, the four printed lines identify the rows and the three state values. Compare row ten's contribution of 220 with the earlier 324. The new accumulator should equal 544.
- Change the Pune amount from 110 to 120 in row four on the copy. The next run gives 554 over the same four matching cities. The trace changes at row four and at each subsequent matched row. That follows from adding ten once. Restore 110 and verify the original total again.
- Clear G4 on the copy while C4 is still Pune. The macro exits with a row-specific message after reading that cell and should not display a final accepted total. It may still have printed the first matching partial amount to Immediate. Your separate SUMIF may ignore the blank and give 434, so do not read its number as proof of four complete amounts. Restore the numeric 110 before the next lab.
- Check the worksheet inputs and K2 marker. The code never assigns a cell value. If you cannot run it, make a running table in a notebook and show the amount and remaining total at every row, including the unchanged totals after a nonmatch.
=SUMIF(C2:C11,"Pune",G2:G11)
=COUNTIF(C2:C11,"Pune")
Carry the amount through four matches
Row 2 starts the total
Add 64 to zero. Row 3 is Nashik, so the total is still 64 after it.
Row 4 adds 110
The total becomes 174. Nagpur and Kolhapur do not change it.
Row 7 adds 150
The total becomes 324. The next two locations do not match Pune.
Row 10 adds 220
The total becomes 544. Nashik on row 11 is visited but adds nothing. Exactly four rows matched.
Lab two. Compare a collection loop and a bounded search
Let each amount cell supply the current row
The second question includes every Delivered order. The collection is the ten cells in G2:G11. Each visit receives one cell object. Since Status is in column I, the status for that record is two columns to the right of the current amount. A direct row number is not needed to reach it. The loop still uses the original row relationship, so there is no sorting or separate group of status values.
Public Sub TotalDeliveredAmounts()
Dim ws As Worksheet
Dim amountCell As Range
Dim rawStatus As Variant, rawAmount As Variant
Dim deliveredCount As Long
Dim total As Double
Set ws = ThisWorkbook.Worksheets("Orders")
For Each amountCell In ws.Range("G2:G11")
rawStatus = amountCell.Offset(0, 2).Value2
If VarType(rawStatus) <> vbString Then
MsgBox "Review the status on row " & amountCell.Row
Exit Sub
End If
If StrComp(Trim$(CStr(rawStatus)), "Delivered", vbTextCompare) = 0 Then
rawAmount = amountCell.Value2
If VarType(rawAmount) <> vbDouble Then
MsgBox "Review the delivered amount on row " & amountCell.Row
Exit Sub
End If
deliveredCount = deliveredCount + 1
total = total + rawAmount
End If
Next amountCell
Debug.Print "Delivered order count", deliveredCount
Debug.Print "Delivered amount total", total
End Sub
- Place the Sub below the first routine in the same standard module. Before running it, identify seven Delivered rows: two, three, four, six, seven, eight and eleven. Add their amounts separately and expect 2,215. Compare their original order IDs as well as the count.
- Run the routine from the practice workbook. Open Immediate in the Visual Basic Editor and find the latest two output lines. Expect the count seven and amount total 2215. Use the independent formulas below for the unmodified fixture. The largest delivered amount, 1299, is in Solapur and still counts because this question uses status across all cities.
- In the copied data change I10 from Cancelled to Delivered without touching its numeric amount of 220. After the run, the delivered group has eight rows and 2435. The all-status Pune total is still 544 because its rule only depends on city and amount. Restore I10 to Cancelled and compare both totals again.
- Inspect K2 and the source range. No flags are written back by this loop. The editor messages are a diagnostic from your run, not a worksheet update. If you want a later report to display the outcome, declare where to store it and perform the write only after checking that the whole loop completed.
=COUNTIF(I2:I11,"Delivered")
=SUMIF(I2:I11,"Delivered",G2:G11)
Stop at the first truly empty ID within the fixture
The third question concerns continuity. In the original compact fixture all ten ID cells have a value. A scanner can check whether any position within A2:A11 is truly empty. If it finds one, report its row. If there is no gap, report that the next position after this known scope is row twelve. Whether there is actually an ID at row twelve is a separate question. That cell is outside the read boundary for the loop.
Public Sub FindFirstIdGap()
Dim ws As Worksheet
Dim rowNo As Long
Dim idValue As Variant
Set ws = ThisWorkbook.Worksheets("Orders")
rowNo = 2
Do While rowNo <= 11
idValue = ws.Cells(rowNo, 1).Value2
If IsEmpty(idValue) Then Exit Do
rowNo = rowNo + 1
Loop
If rowNo <= 11 Then
Debug.Print "Empty ID found on row", rowNo
Else
Debug.Print "No empty ID through row 11. Next row", rowNo
End If
End Sub
- Run FindFirstIdGap on the complete list. Observe the no-gap message with next row 12. Confirm separately that A12 is empty in the original fixture. The code itself only observes rows two through eleven. If you add a value to A12, its conclusion about the inspected scope stays the same.
- In an independent copy clear only A6. Predict a gap on row six. The search stops there even though rows seven through eleven have IDs. Verify the values after the gap can still exist. The first missing ID and last nonempty ID are different questions.
- Test A2 cleared in the isolated copy. The search should report row two immediately. If you place a formula that returns an empty string in A2 instead, it holds a string result. IsEmpty does not report that as truly empty. Use the definition required by the report before changing the test condition.
- Restore all original IDs and verify no gap again. If you cannot run the test, mark the index before and after each visit on paper, and stop when the row's condition or explicit boundary says to stop. No change to your live data or settings is necessary.
Test how a loop ends
Give a small loop a firm boundary
A Do loop with a condition at the top can be read as a sequence of checks. In the gap demo, the current row begins at two. Each time it is within the known range, read exactly one ID value. Determine whether to exit the loop. If the ID is present, add one to the counter. Once the counter is twelve, the top condition is false and the body cannot read A12. There is no need to combine the loop's numeric bound and a worksheet access in one expression. An equivalent top condition for this scan is to continue until the row number is greater than eleven. Keep the same early exit for a discovered gap. VBA does not supply short-circuit And here to protect an out-of-range reference.
Set a useful maximum scope before designing a real import scan. “Check until blank” is not sufficient when missing IDs can occur in the middle of your data. In the tiny fixture, finding a first gap is intentionally the objective. When you need the last used input row, inspect the column or Table that defines record boundaries, as in the next lesson. Detecting internal gaps can be a separate quality check before you process those records.
Compare reverse order without deleting any records
With a For loop you can use a negative Step. Starting at eleven and ending at two with Step minus one visits 11, 10 and so on through 2. It reverses the order, but adding the same valid whole-number amounts in this example produces the same total. The intermediate trace is different. The first encountered Pune row is row ten and the running total starts with 220. The next one is row seven, bringing it to 370. Rows four and two bring it to 480 and 544.
For rowNo = 11 To 2 Step -1
Debug.Print rowNo
Next rowNo
Use a reverse traversal when an action changes row positions and you need a deliberately specified strategy. For example if you manually remove a row from a small list, rows below can move up. A forward counter advancing immediately after a removal can miss the row that moved into its old position. This lesson checks the direction by printing row numbers, which leaves your source intact. If you eventually need deletions in a separate exercise, first mark the candidate records and review them before acting on an approved copy.
Transfer the loop to one small output column
Give every completed iteration a result
The original lesson also labels delivery timing row by row. Start from a disposable copy after finishing the two read-only exercises. Add the actual sample elapsed minutes in column H: nine, twelve, fourteen, eleven, sixteen, eight, eighteen, ten, thirteen and seventeen in rows two through eleven. Reserve J2:J11 for ten outputs. In this exercise a Delivered record above fifteen minutes is Late, a Delivered record at or below fifteen is On time, and other statuses need their own labels. The lesson classifies status and minutes before writing. That way an unknown or invalid row does not silently become On time.
Public Sub MarkPracticeDeliveryRows()
Dim ws As Worksheet
Dim rowNo As Long
Dim state As String
Dim raw As Variant
Dim minutes As Variant
Dim tags(1 To 10, 1 To 1) As Variant
Set ws = ThisWorkbook.Worksheets("Orders")
For rowNo = 2 To 11
state = ""
raw = ws.Cells(rowNo, 9).Value2
If VarType(raw) = vbString Then
state = UCase$(Trim$(CStr(raw)))
End If
minutes = ws.Cells(rowNo, 8).Value2
If state = "CANCELLED" Or state = "RETURNED" Or state = "PENDING" Then
tags(rowNo - 1, 1) = "Timing not applicable"
ElseIf state <> "DELIVERED" Then
tags(rowNo - 1, 1) = "Review status"
ElseIf VarType(minutes) <> vbDouble Then
tags(rowNo - 1, 1) = "Review minutes"
ElseIf minutes < 0 Then
tags(rowNo - 1, 1) = "Review minutes"
ElseIf minutes > 15 Then
tags(rowNo - 1, 1) = "Late"
Else
tags(rowNo - 1, 1) = "On time"
End If
Next rowNo
ws.Range("J2:J11").Value2 = tags
End Sub
The temporary array has ten rows and one column. Worksheet row two maps to its first row because two minus one is one. The last source row eleven maps to array position ten. Each branch assigns a label for its own row. The final assignment writes the dimensions that exactly match J2:J11. You can think of the array as a draft in memory. The worksheet receives the new labels only after the loop has collected them all.
- Start by predicting the late row IDs from the ordered source. Rows 6, 8 and 11 have greater than fifteen minutes and are Delivered. There are three late results. Four other delivered rows are on time: two, three, four and seven. Three more rows are outside timing classification. The counts add to ten.
- Leave the previous results visible and clear H6. Rerun on the copy. Expect J6 to change from Late to Review minutes without changing J8 or J11. The overall results still cover ten rows. Restore the original numeric sixteen for the next comparison.
- Now change status in I6 to a blank value in the copy and rerun. Expect Review status. The variable state resets for every row. Without that reset a blank source status could leave the previous status in memory and misclassify the current order. Restore Delivered and sixteen minutes, then confirm three Late again.
- Check K2 and the source columns after testing. The writes belong only to J2:J11, and the earlier Pune and Delivered amounts remain the same if the source is restored. A changed data value elsewhere would tell you to inspect the exact effect before adapting the routine.
Verify one nonmatching row before increasing the scope
BLK-1004 is Cancelled and has an elapsed value of eleven. The elapsed value alone would meet the On time condition. The status takes precedence, so its result is Timing not applicable. This row and a late delivered row reveal different classes of error. Check both. An array that aligned with the wrong worksheet row could place a good label beside the wrong order. Use the source order IDs when verifying the result.
Debug and extend a repeated action without guessing
Compare how a change affects the trace
- Missing final record: A For ending at ten skips row eleven. It would leave the Pune total of 544 unchanged, since the last row is Nashik. The Delivered amount would lose 90 if that bound also applied to its loop. Verify a visit count or last-record ID independently of the Pune answer. One correct total can hide an off-by-one mistake when a nonmatching row is omitted.
- Early termination: The gap scan stops at the first truly empty ID. The For loop will keep examining the declared row numbers even if an ID is missing, because it checks the city and amount fields. If a valid ID is required to count a row, add that requirement as another explicit source check rather than assuming the loop finds it automatically.
- Stale variables: Reset any temporary status or flag when a previous value must not carry into the next row. The total is an exception by design: it carries forward during the same run. A routine-level Dim total starts at zero for a new normal call, while a persistent variable might keep earlier state. Keep deliberate carry-forward separate from per-row values.
- Incorrect offset after a layout change: The delivered loop reads two columns to the right of each G cell. If the status moves from I to J, that expression sees the wrong field. Read the source header and sample field before rerunning. Changing a constant or using a named structured column is appropriate only after confirming the current layout.
- Partial trace from an invalid record: If a matching row has invalid amount text, earlier Debug.Print lines may remain. The absence of the final accepted result matters. Report the first erroneous row separately and remind the reviewer that the trace was incomplete. Correct the input or explicitly specify a different rule for missing amounts.
Choose a familiar calculation when you do not need a custom action
The practice makes small source visits visible. A worksheet SUMIF already handles the simple sum for a known city on clean data, and a COUNTIF gives the matching count. Use a loop when the task needs several custom checks, traces or output decisions for different rows. On a larger dataset, readings through each Excel cell object can add overhead. A carefully tested array read or built-in worksheet calculation may serve the same report more directly. Measure the work in realistic conditions before making a speed claim.
If source criteria contain extra spaces or unexpected types, the sample loop's Trim and strict number checks may produce a different outcome from SUMIF. The fixture is deliberately clean so the two methods provide an independent verification. Extend your tests with a known trimmed label and a missing amount before assuming identical behavior for all possible imports. Explain which source assumptions make the comparison valid.
Describe the stop condition: Give the first and last row of the For loop, the range supplied to For Each and the bound and first-gap rule for Do While. Then choose one row from the original fixture and describe which of the three routines observes it, counts it or stops before it.
Compare sequential visits with a different step size
Work an exact exercise without touching the source
Some manuals show a For loop with Step 2 to skip every other position. This means every other row in its current layout. It does not mean every other matching record. Try writing the trace for For rowNo = 2 To 11 Step 2. It visits 2, 4, 6, 8 and 10. Pune matches at coordinates 2, 4 and 10 in this subset, giving 64 + 110 + 220 = 394. Row 7 is a Pune record in the original data but is never visited. Replacing Step 1 with Step 2 would incorrectly change the all-rows report.
Now try the counterpart beginning at row three and using the same step size. It visits 3, 5, 7, 9 and 11. Only row 7 matches Pune and contributes 150. The two disjoint visit sets together cover the original ten rows. Their two Pune subtotals add to 544. This can be a useful diagnostic of the two experimental runs, even though the real task uses one consecutive range. Starting either set on a different row changes which source records it sees. Sort or insert rows and those same physical positions may represent different IDs.
Keep the distinction between skipping positions and filtering records. A filter rule based on city reads a row and then decides whether to include it. A step greater than one can skip some records before the code even reads their cities. If your sheet stores one record over two physical rows, such as a data row followed by a fixed detail row, a step of two may be intentional. First verify that the expected alternating layout exists throughout the whole input. Adding a note between rows must not silently change which rows are treated as records. Either define a reliable layout boundary or identify the rows by their own fields.
Read the trace for a first-hit search
Suppose the request is “Which is the first Pune record in this worksheet order?” A complete total is unnecessary. The answer is BLK-1001 in row two for the original fixture. If you scan from the bottom instead, the first Pune match encountered is BLK-1009 at row ten. That is the last Pune record in the original display order. A routine using Exit For after a successful match should say which traversal order it uses. Sorting by another field can change these answers without changing the set of Pune records or their amounts.
Now request the first row with a nonexistent city. The loop cannot find a match. Use a separate match flag or explicit default result to tell the caller that the search failed. An uninitialized numeric result of zero is not a valid row in the Excel worksheet. Display “No matching row in 2–11” so the person reading it knows what was actually searched. If the search needs a valid order ID before claiming success, check that field before providing the row as an answer.
Plan an independent test after editing the worksheet
Copy the worksheet into a new practice file, keep the read-only version, then alter one record only if you can describe its new expected contribution. For example choose row seven and make its amount zero without changing its city. The all-status Pune count stays four. Its total drops from 544 by 150 to 394. The original Step 2 subset also gave 394, but it matched three rows instead of four. The same total can indicate different source decisions. Check the match count and four contributing IDs instead of inferring the set from the total alone.
Write both versions in your run notes: “All Pune rows with a valid zero included” and “Only even physical rows checked.” Your teammate can see that the reported sums happen to agree and the two questions are still distinct. Explain which result belongs to the report before enabling a new action on a larger set of records.
Quick checks
Read the iteration before reading the final answer
How many positions does For rowNo = 2 To 11 visit?
It visits ten row numbers when it completes without an early exit. Both endpoints are included. Four city cells match Pune, while the other six still get examined. Compare the visited and matched sets separately, since a correct Pune total cannot prove a final Nashik row was checked.
What is the Pune total immediately after row four?
It is 174. Row two contributed 64, row three did not match, and row four contributed 110. Keep the order ID or row number beside each amount in a trace. If you process the same source in reverse order, the intermediate total changes while the final sum of these integer amounts stays the same.
What row does an amount cell in G7 read with an offset of zero rows and two columns?
It reads I7, the same row's status. Column G is seven and the two-column right shift reaches nine. The offset does not move the row. With Delivered in I7, that amount belongs to the delivered count and total.
Does the bounded gap scanner examine A12 when it reports next row 12?
No visit to A12 is made. After processing row eleven, the counter reaches twelve and the top condition fails. The message reports the first position beyond its declared scope. Check the actual cell independently if you need to know whether it is empty.
How does a formula returning empty text compare with an actually blank ID?
The stored result of the formula is an empty String, so the IsEmpty test for a truly blank cell is false. A cleared cell returns Empty for this practice check. If a report groups both as missing IDs, define another explicit test and verify both inputs rather than changing the boundary by guesswork.
Which original ranges should the read-only routines change?
They should make no worksheet edits. They read city, status and amounts or the ID gap, then show a message or print diagnostics. A separate optional label routine owns J2:J11. Check K2 and the input cells after either route to verify that they stayed within their intended boundaries.
Interview and discussion
Justify a repeat pattern from the record boundary
When would you use a numbered For loop rather than For Each?
Use numbered iteration when the row position is central, such as pairing city and amount cells by a row number and writing to a same-row output. For Each is clear when the object collection is the starting point. It can also read an item's position from its Range object when needed. Both should name the workbook and scope.
How do you avoid an endless Do scan?
Start from a known index and set an outer bound. Inside the loop, either exit for a documented match or advance toward the boundary. In the gap example the maximum is row eleven, so a continuous list leads to twelve and stops. Test a gap at the first row and a complete region.
Why check for an invalid amount before adding it?
A row can satisfy the grouping rule with a missing or textual amount. Adding it without a check can raise an error or silently change the measured value. The exercise reports the exact row and omits the final accepted summary on failure. A partial sum is useful for debugging but has different meaning from the verified total.
How would you test that the status change affected only the intended aggregate?
Change the cancelled Pune row at row ten to Delivered in the copied data. The all-city delivered total should increase from 2215 to 2435 and its count from seven to eight. The Pune all-status total remains 544. Looking at both outputs proves they respond to the criteria they claim to use.
Why can a reversed loop help if a later approved task removes rows?
With normal upward movement after deleting one row, a forward counter can pass the row that just shifted into the deleted position. Reversing from the last row avoids revisiting lower positions that have already been inspected in that particular design. First test the candidates without performing a destructive action. Verify the source boundaries and ownership before any later change.
Six recall cards
- Count iterations
Rows 2 through 11 are ten visits. Four matches add to the 544 Pune total.
- Check the collection
For Each amount cell can read the same row's status two columns to the right.
- Separate scopes
Delivered across all cities gives seven rows and 2215. Pune across all statuses gives four and 544.
- Advance toward a stop
The Do scanner either finds a gap or increases its row number until the known bound prevents a further read.
- Meaning of empty
A genuinely blank cell can make IsEmpty true. A formula result containing empty text is a string instead.
- Protect the output
Reserve one label range. Check the source row and running value before writing the results of repeated logic.
Microsoft references
Continue practising: explore the existing Excel Task Hub for additional exercises.