Loop Structures: while Loop

The for loop iterates over a fixed-length iterable object (known number of iterations). For cases where the number of iterations is unknown (loops until a condition is met), use the while loop.

Simple while Loop

[Excel VBA] Excel VBA has two While loop forms: Do...Loop and While...Wend.

Do...Loop syntax:

code.vba
Do While condition
    statements
Loop

Or:

code.vba
Do
    statements
Loop While condition

The first form checks the condition first; the second executes statements first, then checks the condition.

While...Wend is similar to the first Do...Loop form (checks condition first).

[Python] The simple while loop evaluates the condition first. If true, it executes the loop body; otherwise, it skips. Syntax:

code.python
while condition:
    statements...

Python does not have the second form of Do...Loop.

The following example uses a simple while loop to find the greatest common divisor (GCD) and least common multiple (LCM) of two natural numbers.

Algorithm for GCD:

Given two natural numbers m and n (assume m > n).

Compute r = m % n (remainder of m divided by n).

If r = 0, n is the GCD; end. Otherwise, proceed to step 4.

Set m = n, n = r, and repeat step 2.

LCM = (product of m and n) / GCD.

[Excel VBA] Sample file path: Samples\ch05\Excel VBA\WhileLoop.xlsm

code.vba
Sub Test()
    Dim lngM As Long, lngN As Long, lngR As Long  ' GCD
    Dim lngB As Long  ' LCM
    Dim lngM0 As Long, lngN0 As Long  ' Original values
    lngM = 100: lngN = 15  ' Given m > n
    lngM0 = 100: lngN0 = 15
    If lngM < lngN Then
        MsgBox "The first number must be larger than the second."
        Exit Sub
    End If
    lngR = lngM Mod lngN  ' Compute remainder
    Do While lngR <> 0  ' Repeat until remainder is 0
        lngM = lngN
        lngN = lngR
        lngR = lngM Mod lngN
    Loop
    lngB = lngM0 * lngN0 / lngN  ' Compute LCM
    Debug.Print "GCD: " & CStr(lngN)
    Debug.Print "LCM: " & CStr(lngB)
End Sub

Output in the Immediate Window:

code.vba
GCD: 5
LCM: 300

[Python] Sample .py file path: Samples\ch05\Python\sam05-011.py

code.python
m = 100: n = 15  # Given m > n
m0 = 100: n0 = 15
if m >= n:
    r = m % n  # Compute remainder
    while r != 0:  # Repeat until remainder is 0
        m = n
        n = r
        r = m % n
    b = m0 * n0 / n  # Compute LCM
    print('GCD: ' + str(n))
    print('LCM: ' + str(b))

Output in the IDLE command-line window:

code.python
>>> = RESTART: ...\Samples\ch05\Python\sam05-011.py
GCD: 5
LCM: 300.0

Branched while Loop in Python

Python’s branched while loop includes an else block. Syntax:

code.python
while condition:
    statements...
else:
    statements...

If the condition is met, the first block executes; if not, the else block executes.

The following example uses a branched while loop to accumulate integers from 1 to 10 and tell when the iteration variable exceeds 10.

Sample .py file path: Samples\ch05\Python\sam05-012.py

code.python
sum = 0: n = 0
while n <= 10:  # Accumulate sum
    sum += n
    n += 1
else:  # Execute when n > 10
    print("Number exceeds 0~10 range; calculation terminated.")
print(sum)

Output in the IDLE command-line window:

code.python
>>> = RESTART: ...\Samples\ch05\Python\sam05-012.py
Number exceeds 0~10 range; calculation terminated.
55

Nested while Loops

The following example uses nested while loops to generate the multiplication table.

[Excel VBA] Sample file path: Samples\ch05\Excel VBA\WhileLoop.xlsm

code.vba
Sub Test2()
    Dim intI As Integer, intJ As Integer
    intI = 0
    Do While intI < 9
        intJ = 0
        intI = intI + 1
        Do While intJ < intI
            intJ = intJ + 1
            Debug.Print CStr(intJ) & "*" & CStr(intI) & "=" & Trim(CStr(intJ * intI)) & " ";
        Loop
        Debug.Print  ' New line
    Loop
End Sub

Output in the Immediate Window (multiplication table).

[Python] Sample .py file path: Samples\ch05\Python\sam05-013.py

code.python
i = 0
while i < 9:  # Outer loop
    j = 0
    i += 1
    s = ''
    while j < i:  # Inner loop
        j += 1
        s += str.format('{0}*{1}={2} ', i, j, i * j)
    print(s)

Lines 1–8 generate the multiplication table. The output matches the Excel VBA result.

Example: Find Maximum and Minimum Values with while Loop

This section uses a while loop to solve the max/min problem from Section 5.2.4.

[Excel VBA] Sample file path: Samples\ch05\Excel VBA\FindMaxMin_WhileLoop.xlsm

code.vba
Sub MaxMin()
    Dim intI As Integer
    Dim sngMax As Single, sngMin As Single  ' Store max/min
    Dim sngT As Single
    Dim intN As Integer, intRows As Integer
    ' Get the last row of data in Column A
    intRows = ActiveSheet.Range("A1").End(xlDown).Row
    intN = 1  ' Initialize row counter
    ' Initialize max/min with the first value
    sngMax = ActiveSheet.Cells(1, 1).Value
    sngMin = ActiveSheet.Cells(1, 1).Value
    ' Loop until intN reaches the last row
    Do While intN < intRows
        intN = intN + 1
        sngT = ActiveSheet.Cells(intN, 1).Value
        If sngT > sngMax Then sngMax = sngT  ' Update max
        If sngT < sngMin Then sngMin = sngT  ' Update min
    Loop
    ' Output results
    ActiveSheet.Cells(2, 4).Value = sngMax
    ActiveSheet.Cells(3, 4).Value = sngMin
End Sub

Running the program outputs the max/min in the worksheet (Figure 5-2).

[Python] Sample data file: Samples\ch05\Python\FindMaxMin_WhileLoop.xlsx Sample .py file: sam05-03.py

code.python
class="text-secondary">import xlwings class="text-secondary">as xw
class="text-secondary">from xlwings.constants class="text-secondary">import Direction
class="text-secondary">import os
root = os.getcwd()
app = xw.App(visible=True, add_book=False)
bk = app.books.open(fullname=root + r'\FindMaxMin_WhileLoop.xlsx', read_only=False)
sht = bk.sheets(1)  # Get the first worksheet
# Get the last row of data in Column A
rows = sht.api.Range('A1').End(Direction.xlDown).Row
max_v = sht.range('A1').value
min_v = sht.range('A1').value
n = 1
# Iterate through data cells
while n < 9:  # Adjust based on actual data rows
    n += 1
    tp = sht.cells(n, 1).value  # Get the value
    if tp > max_v: max_v = tp  # Update max
    if tp < min_v: min_v = tp  # Update min
# Output results
sht.cells(2, 4).value = max_v
sht.cells(3, 4).value = min_v

Running the program outputs the max/min in the worksheet (Figure 5-2).