12.10 Loops: For, For Each and Do
Sub LoopExamples()
Dim ws As Worksheet
Dim r As Long
Dim cell As Range
Dim total As Double
Set ws = ThisWorkbook.Worksheets("Orders")
' 1) For...Next with a counter: mark late deliveries
For r = 2 To 11
If ws.Cells(r, 8).Value > 15 Then
ws.Cells(r, 10).Value = "Late"
Else
ws.Cells(r, 10).Value = "On time"
End If
Next r
' 2) For Each over cells: add up delivered amounts
For Each cell In ws.Range("G2:G11")
If cell.Offset(0, 2).Value = "Delivered" Then total = total + cell.Value
Next cell
Debug.Print "Delivered sales: "; total
' 3) Do While: move down until an empty cell
r = 2
Do While ws.Cells(r, 1).Value <> ""
r = r + 1
Loop
Debug.Print "First empty row: "; r
End Sub
On the mini dataset: rows 6, 8 and 11 are "Late"; the Immediate window prints Delivered sales: 2215 and First empty row: 12. Other forms: For r = lastRow To 2 Step -1 (loop backwards – needed when deleting rows), Do Until … Loop, and Exit For / Exit Do to leave early.
Ravindra Bagale's Tip
Rows delete karnara loop khalun varti (Step -1) chalvaycha – khup students varun khali chalvtat, mag row delete jhali ki khalchi row varti yete aani loop ti skip karto. Ani Do While madhe counter vadhavayla (r = r + 1) visarla tar infinite loop hoto – thambavayla Esc kiwa Ctrl + Break daba.
Practice task
Loop through the orders and write the delivery fee (4.9 slabs) in a new column. Then write a backwards loop that deletes all Cancelled rows on a copy of the data.