DoWhile loop

VBA supports another type of looping structure known as a Do-While loop. Unlike a For-Next loop, a Do-While loop continues until a specified condition is met. Here's the Do-While loop syntax:

Do [While condition] [statements] [Exit Do] [statements]

The following example uses a Do-While loop. This routine uses the active cell as a starting point and then travels down the column, multiplying each cell's value by 2. The loop continues until the routine encounters an empty cell.

Sub DoWhileDemo()

Do While ActiveCell.Value <> Empty

ActiveCell.Value = ActiveCell.Value * 2 ActiveCell.Offset(1, 0).Select

Loop End Sub

Some people prefer to code a Do-While loop as a Do-Loop While loop. This example performs exactly as the previous procedure but uses a different loop syntax:

Sub DoLoopWhileDemo() Do

ActiveCell.Value = ActiveCell.Value * 2 ActiveCell.Offset(1, 0).Select Loop While ActiveCell.Value <> Empty End Sub

Remember this key difference between the Do-While and Do-Loop While loops: The Do-While loop always performs its conditional test first. If the test is not true, the instructions inside the loop are never executed. The Do-Loop While loop, on the other hand, always performs its conditional test after the instructions inside the loop are executed. Thus, the loop instructions are always executed at least once, regardless of the test. This difference can make a profound difference in how your program functions.

0 0

Post a comment