See Also Example
Executes a series of statements in a loop as long as a given condition is true.
The While...Wend statement has these parts:
While Begins the While...Wend loop control structure.
condition Any numeric or string expression 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.
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.
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
Msg = "Sorted order: " & NL & NL ' Create message that shows
For I = 1 To MAX ' sorted order of array
Msg = Msg & A(I) & NL ' contents.
MsgBox Msg ' Display message.