VBA While Wend Loop

Written by

Mel Jenkins

Reviewed by

Steve Rynearson

Last updated on January 25, 2024

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.

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.

Sub TestWhileWend()
  Range("A1").Select
  While ActiveCell > 5
    ActiveCell.Font.Color = vbRed
    ActiveCell.Offset(1, 0).Select
  Wend
End Sub

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.

Sub NestedWhileWend()
  Dim r As Integer
  Dim c As Integer
  r = 1
  c = 2
  Cells(r, 1).Select
  While ActiveCell > 20
     ActiveCell.Font.Color = vbRed
     While Cells(r, c) > 30
      Cells(r, c).Font.Color = vbGreen
      c = c + 1
     Wend
  c = 2
  r = r + 1
  Cells(r, 1).Select
  Wend
End Sub

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!
vba-free-addin

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

(No installation required!)

Free Download

Return to VBA Code Examples