Return to VBA Code Examples

VBA While Wend Loop

This tutorial will demonstrate how to use the While Wend Loop in VBA.

Loops, Case Statements and If Statements are an intricate part of all programming languages.  Understanding how these routines work in VBA is essential to mastering VBA correctly.  The While Wend Loop is one of the simplest loops available in VBA and is still included in VBA to make it compatible with older VBA code.  The newer Do and For loops are much more efficient and are preferable to use.

Using the While Wend Loop

The While Wend loop will run while the condition that we are testing for remains TRUE.  As soon as the condition returns FALSE, the loop will stop running.

If we were to run this loop starting in cell A1 on the data below, the loop would run until it gets to cell A5, the value of which is not greater than 5 – and therefore the loop would stop – it would not go any further even though the cells from row 6 down are greater than 5 as the loop runs WHILE the condition of the loop is TRUE – when it gets to cell A5, the condition of the loop returns FALSE so the loop stops.

VBA While Wend Example

 

Nested While Wend Loop

To add a further condition to the While Wend loop, we can use a Nested Loop.

Running this loop above on the data below will result in the following:

VBA While Wend Nested Example

Disadvantages of the While Wend Loop

  1. You cannot exit the loop like you can in the Do (Exit Do) or For (Exit For) Loops.
  2. You run the risk to creating a perpetual loop if you make a mistake in your code which you might then have to press Ctl+Alt+Delete to exit Excel in order to stop the code from continuing to run!   However this disadvantage is in every type of looping structure if the code is not constructed correctly!

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users! vba save as


Learn More!