While...Wend Statement

See Also1IFHEPP              Example1VITATS>Low

Executes a series of statements in a loop as long as a given condition is true.

Syntax

While condition
          [statementblock]

Wend

The While...Wend statement has these parts:

Part                        Description

 

While                      Begins the While...Wend loop control structure.

condition                  Any numeric71RISN or string expression1330R89 that evaluates true (nonzero) or false (0 and Null1DDW7C0).  If condition is true, all statements in statementblock are executed until the Wend statement is encountered.  Control then returns to the While statement and condition is again checked.  If condition is still true, the process is repeated.  If it is not true, execution resumes with the statement following the Wend statement.

statementblock         Any number of Visual Basic statements on one or more lines.

Wend                      Ends the While...Wend.

Remarks

While...Wend loops can be nested to any level.  Each Wend matches the most recent While.

 

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 program problems that are difficult to locate.

 

Tip     The Do...Loop statement provides more structure and a more flexible way to perform looping.

 


See Also

Do...Loop StatementLANDO


While...Wend Statement Example

The example uses While...Wend in a sorting routine.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

 

Sub Form_Click ()

   Const MAX = 5                         ' Declare constant.

   Dim Exchange, I, Msg, NL, Temp        ' Declare variables.

   Static A(MAX)                         ' Declare an array.

   NL = Chr(13) & Chr(10)                ' Define newline.

   A(1) = "New York"                     ' Put data in array in no

   A(2) = "Paris"                        ' particular order so it

   A(3) = "Chicago"                      ' can be sorted.

   A(4) = "London"

   A(5) = "Berlin"

   Exchange = True                       ' Force 1st pass through array.

   While Exchange                        ' Sort until no elements are

      Exchange = False                   ' exchanged.

      ' Compare array elements by pairs.  When two are exchanged,

      ' force another pass by setting exchange to TRUE.

      For I = 2 To MAX

         If A(I - 1) > A(I) Then

            Exchange = True              ' Make swap.

            Temp = A(I): A(I) = A(I - 1): A(I - 1) = Temp

         End If

      Next I

   Wend

   Msg = "Sorted order: " & NL & NL      ' Create message that shows

   For I = 1 To MAX                      ' sorted order of array

      Msg = Msg & A(I) & NL              ' contents.

   Next I

   MsgBox Msg                            ' Display message.

End Sub