Article ID: 141762
Article Last Modified on 1/19/2007
Do I know exactly how many times I want to loop through the code?
If so, how many?
If not, is there a specific condition on which I want the macro to
exit the loop? If the loop is conditional, do I want to test the
condition before or after the code is executed?
' To show the contents of each cell in a selection or specific range.
Sub for_each_demo()
' Or, use "In Worksheet(~).Range(~)" to specify a specific range.
For Each cell In Selection
' Displays cell contents in message box.
MsgBox cell.Value
' Reset cell to next object.
Next
End Sub
' This example loops through the code a specified number of times.
Sub for_demo()
' Sets x to 1, adds 1 to x until x = 5, loops 5 times.
For x = 1 To 5 Step 1
' Displays value of x in msgbox.
MsgBox x
' Returns to top of loop 4 times.
Next
End Sub
' Performs Do loop, testing at top of loop.
' Loops until empty cell is reached.
' Note that you can also use a Do While Not IsEmpty(ActiveCell) loop.
Sub test_before_do_loop()
' Test contents of active cell; if active cell is empty, exit loop.
Do Until IsEmpty(ActiveCell)
' Displays cell contents in message box.
MsgBox ActiveCell.Value
' Step down 1 row to the next cell.
ActiveCell.Offset(1, 0).Select
' Return to top of loop.
Loop
End Sub
' Performs Do loop, testing at bottom of loop.
Sub test_after_do_loop()
' Test to see if first cell is empty.
If IsEmpty(ActiveCell) Then Exit Sub
' Begin loop.
Do
' Displays cell contents in message box.
MsgBox ActiveCell.Value
' Steps down one row to the next cell.
ActiveCell.Offset(1, 0).Select
' Test contents of active cell; if empty, exit loop
' or Loop While Not IsEmpty(ActiveCell).
Loop Until IsEmpty(ActiveCell)
End Sub
CAUTION: Do not branch into the body of a While...Wend loop without executing the While statement. Doing so may cause run-time errors or other problems that are difficult to locate.
' Performs While loop, testing at top of the loop.
Sub While_loop_demo()
' Sets condition of loop, while active cell is not empty.
While Not IsEmpty(ActiveCell)
' Displays cell contents in message box.
MsgBox ActiveCell.Value
' Step down one row to the next cell.
ActiveCell.Offset(1, 0).Select
' End While loop.
Wend
End Sub
Sub loop_using_goto()
' Test to see if first cell is empty.
If IsEmpty(ActiveCell) Then Exit Sub
' Line label indicating top of loop.
top:
' Displays cell contents in message box.
MsgBox ActiveCell.Value
' Step down one row to the next cell.
ActiveCell.Offset(1, 0).Select
' Test to see if new cell is empty.
If Not IsEmpty(ActiveCell) Then GoTo top
End Sub
305326 OFFXP: Programming Resources for Visual Basic for Applications
226118 OFF2000: Programming Resources for Visual Basic for Applications
163435 VBA: Programming Resources for Visual Basic for Applications
Additional query words: 8.00 xl97 VBA loop howto
Keywords: kbcode kbhowto kbprogramming KB141762