Other Statements

Previous sections introduced common syntax structures in Excel VBA and Python. Additionally, both languages have special statements for breaking out,(jumping, terminating and placeholder operations.

Other Statements in Excel VBA

Excel VBA includes End, Exit, GoTo, and Stop statements.

End Statement: Immediately terminates macro execution. If the macro is called by another macro via MacroRun, the calling macro continues after MacroRun.

Exit Statement: Stops executing the remaining statements in the macro. Syntax:

Exit {All|Do|For|Function|Property|Sub|While}

Do: Exit a Do loop.

For: Exit a For loop.

Function: Exit a function block (clears Err and sets Error$ to empty).

Property: Exit a property block (clears Err and sets Error$ to empty).

Sub: Exit a procedure block (clears Err and sets Error$ to empty).

GoTo Statement: Jumps to a label and continues execution from there (only within the current procedure, function, or property).

Stop Statement: Pauses execution. To resume, start from the next statement.

Example: Pause when I = 3:

code.vba
Sub Main()
    For I = 1 To 10
        Debug.Print I
        If I = 3 Then Stop
    Next I
End Sub

Other Statements in Python

Python includes break, continue, and pass statements.

break Statement: Terminates and exits a while or for loop when necessary.

The following example uses a for loop to accumulate values in a range, stopping when the sum exceeds 100:

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

code.python
sum = 0: num = 0
for num in range(100):
    old_sum = sum
    sum += num
    if sum > 100: break  # Exit loop when sum > 100
print(num - 1)  # Last number added
print(old_sum)  # Sum ≤ 100

Output in the IDLE command-line window:

code.python
>>> = RESTART: ...\Samples\ch05\Python\sam05-014.py
13
91

The same logic can be implemented with a while loop (sample file: sam05-015.py).

continue Statement: Similar to break, but skips only the current iteration (not the entire loop).

The following for loop outputs integers 0–4 except 3:

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

code.python
for i in range(5):
    if i == 3: continue
    print(i)

Output in the IDLE command-line window:

code.python
>>> = RESTART: ...\Samples\ch05\Python\sam05-016.py
0
1
2
4

pass Statement: A placeholder that does nothing, used to maintain program structure integrity.

In a decision structure, if no statement is executed when the condition is met, an error occurs:

if a > 1: # Do nothing (error)

Adding pass avoids the error:

code.python
if a > 1: pass  # Do nothing(valid)

Similarly, when defining an empty function, pass prevents errors:

code.python
def empty_function():
    pass  # Valid empty function