For next vba excel move to the next one. Loop statements in VBA. Project "Income on Deposit"

There are situations when a VBA program is required to perform the same set of actions several times in a row (that is, repeat the same block of code several times). This can be done using VBA loops.

For Loop Statement in Visual Basic

Loop statement structure For in Visual Basic can be organized in one of two forms: as a loop For…Next or like a cycle For Each.

Cycle “For...Next”

Cycle For…Next uses a variable that sequentially takes values ​​from a given range. With each change in the value of the variable, the actions contained in the body of the loop are performed. This is easy to understand from a simple example:

For i = 1 To 10 Total = Total + iArray(i) Next i

In this simple loop For…Next variable is used i, which sequentially takes the values ​​1, 2, 3, ... 10, and for each of these values ​​the VBA code inside the loop is executed. Thus, this loop sums the elements of the array iArray in a variable Total.

In the above example, the loop increment step is not specified, so to increment the variable i From 1 to 10 the default is increment 1 . However, in some cases it is necessary to use different increment values ​​for the loop. This can be done using the keyword Step, as shown in the following simple example.

For d = 0 To 10 Step 0.1 dTotal = dTotal + d Next d

Since in the above example the increment step is set to 0.1 , then the variable dTotal for each repetition of the cycle takes the values ​​0.0, 0.1, 0.2, 0.3, ... 9.9, 10.0.

To determine the loop step in VBA, you can use a negative value, for example, like this:

For i = 10 To 1 Step -1 iArray(i) = i Next i

Here the increment step is -1 , so the variable i with each repetition of the cycle it takes on the values ​​10, 9, 8, ... 1.

For Each Loop

Cycle For Each looks like a cycle For…Next, but instead of looping through the sequence of values ​​for the counter variable For Each performs a set of actions for each object in a specified group of objects. In the following example, using a loop For Each Lists all sheets in the current Excel workbook:

Dim wSheet As Worksheet For Each wSheet in Worksheets MsgBox "Sheet Found: " & wSheet.Name Next wSheet

Exit For Loop Interrupt Operator

Operator Exit For used to interrupt the cycle. As soon as this statement is encountered in the code, the program ends the execution of the loop and proceeds to execute the statements found in the code immediately after this loop. This can be used, for example, to search for a specific value in an array. To do this, use a loop to look through each element of the array. Once the required element is found, there is no need to look through the rest - the cycle is interrupted.

Operator application Exit For demonstrated in the following example. Here the loop loops through 100 array entries and compares each one with the value of the variable dVal. If a match is found, the loop is interrupted:

For i = 1 To 100 If dValues(i) = dVal Then IndexVal = i Exit For End If Next i

Do While Loop in Visual Basic

Cycle Do While executes a block of code as long as a given condition is met. The following is an example of the procedure Sub, in which, using a loop Do While Fibonacci numbers not exceeding 1000 are displayed sequentially:

"The Sub procedure prints Fibonacci numbers not exceeding 1000 Sub Fibonacci() Dim i As Integer "a counter to indicate the position of an element in the sequence Dim iFib As Integer "stores the current value of the sequence Dim iFib_Next As Integer "stores the next value of the sequence Dim iStep As Integer "stores the size of the next increment "initialize the variables i and iFib_Next i = 1 iFib_Next = 0 "the Do While loop will be executed until the value of the "current Fibonacci number exceeds 1000 Do While iFib_Next< 1000 If i = 1 Then "особый случай для первого элемента последовательности iStep = 1 iFib = 0 Else "сохраняем размер следующего приращения перед тем, как перезаписать "текущее значение последовательности iStep = iFib iFib = iFib_Next End If "выводим текущее число Фибоначчи в столбце A активного рабочего листа "в строке с индексом i Cells(i, 1).Value = iFib "вычисляем следующее число Фибоначчи и увеличиваем индекс позиции элемента на 1 iFib_Next = iFib + iStep i = i + 1 Loop End Sub

In the example given, the condition iFib_Next< 1000 checked at the beginning of the cycle. Therefore, if the first value iFib_Next If it were more than 1000, then the loop would not be executed even once.

Another way to implement a loop Do While– place the condition not at the beginning, but at the end of the loop. In this case, the loop will be executed at least once, regardless of whether the condition is true.

Schematically such a cycle Do While with the condition being checked at the end it will look like this:

Do...Loop While iFib_Next< 1000

Do Until Loop in Visual Basic

Cycle Do Until very similar to a cycle Do While: The block of code in the body of the loop is executed over and over until the specified condition is satisfied (the result of the conditional expression is True). In the following procedure Sub using a loop Do Until extracts values ​​from all cells in a column A worksheet until an empty cell is encountered in the column:

IRow = 1 Do Until IsEmpty(Cells(iRow, 1)) "The value of the current cell is stored in the dCellValues ​​array dCellValues(iRow) = Cells(iRow, 1).Value iRow = iRow + 1 Loop

In the above example the condition IsEmpty(Cells(iRow, 1)) located at the beginning of the structure Do Until, therefore the loop will be executed at least once if the first cell taken is not empty.

However, as was shown in the loop examples Do While, in some situations you want the loop to be executed at least once, regardless of the initial result of the conditional expression. In this case, the conditional expression should be placed at the end of the loop, like this:

Do ... Loop Until IsEmpty(Cells(iRow, 1))

Loop statements

In VBA There are two main types of loops: loops with a counter (parametric) and loops with a condition (iterative).

Counter loops are used in cases where it is necessary to perform certain actions a certain number of times.

Conditional loops are used when certain actions in a program must be repeated until a certain condition is met.

Loops with parameter For…Next

Cycle structure:

For Cycle_parameter = Initial_Value To Final_Value

[Step Step]

Operators

[Exit For]

Next [Cycle_parameter]

where For keyword VBA (from), indicating the beginning of the cycle;

loop_parameter variable defined as a loop counter;

Initial_Value a number that specifies the initial value of the loop parameter;

To keyword VBA (before), dividing

Initial_Value and Final_Knowledge;

Final_Value a number specifying the value of the loop parameter,

At which the cycle ends;

Step keyword VBA (step) used for

Loop step specifications, optional argument;

Step a number specifying the cycle step, i.e. the value by which

Increases (or decreases) the parameter value

Cycle at every step. This number could be

Negative;

Exit For operator of early exit from the loop (optional);

Next keyword VBA (next) denoting

End of the cycle.

Cycle work:

Step 1 First, the loop parameter is determined, and the initial and final values ​​of this variable are calculated and stored.

Step 2 The loop parameter is assigned an initial value.

Step 3 The initial value of the loop parameter is compared with the final value.

If the loop parameter is greater than the final value, the program immediately exits the loop and jumps to the line of code that follows the loop.

Step 4 The body of the loop is executed.

Step 5 After executing the body of the loop, the next value is assigned to the loop parameter. Go to step 3.

Note.

1. If a keyword is used Step , then the loop parameter changes according to the number specified after this word. If the word Step is absent, then the step value is equal to one.

Example 1.

For I = 0 To 10 Step 2 (Value I will increase by 2)

2. For...Next loop can be terminated early when any condition is reached. To do this, at the right place in the loop you need to place the operator Exit For.

Example 2.

Dim S As Integer

Dim j As Integer

S=2

For j = 1 To 10

S = S + j

If S > 6 Then

Exit For (Exit the loop if the value S > 6)

End If

Next j

MsgBox(S)

Conditional Loops (Iterative)

If some action (several actions) needs to be performed many times, but it is not known in advance how many times and this depends on some condition, then you should use a loop with a precondition or a postcondition.

In VBA there are two main loops DO...LOOP with a condition entered by a keyword While , and with the condition entered by the keyword Until . Both of them can be with precondition or postcondition.

Syntax:

where Do keyword (do);

While keyword (yet);

Until keyword (until);

Loop a keyword indicating the end of the cycle;

<условие>a logical expression whose truth is checked

At the beginning of each execution of the loop body;

<тело_цикла>arbitrary sequence of operators;

Do...While construction reads: do while the condition is met. In design Do...While For

The Do...Until construction reads: do until the condition is met. In design Do...Until To increase the step, you should write a special operator, because in it, unlike the design For , this is not done automatically.

Condition written after the keyword Until , is checked at the end of each iteration (after the loop body is executed). Note that it doesn't work exactly the same way as in the loop While . If the condition is true ( True ), then the loop ends. If the condition is not met (is false False ), then the body of the loop is executed again.

Example 1.

Formulation of the problem. Calculate the sum of a finite series using a subroutine procedure.

Task execution technology:

1. Initial data: i  Z

Result: S  R .

2.Type the following custom procedure in the standard project module using a loop with a precondition While:

Sub summa()

Dim S As Integer

Dim i As Integer

S=0

i = 1

Do While i<= 10

S = S + i^2

i = i + 1

Loop

MsgBox(S)

End Sub

3.Type the following custom procedure in the standard project module using a loop with a precondition Until:

Sub summa()

Dim S As Integer

Dim i As Integer

S=0

i = 1

Do Until i > 10

S = S + i^2

i = i + 1

Loop

MsgBox(S)

End Sub

4 Type the following custom procedure in the standard project module using a loop with a postcondition While:

Sub summa()

Dim S As Integer

Dim i As Integer

S=0

i = 1

S = S + i^2

i = i + 1

Loop While i<= 10

MsgBox(S)

End Sub

5 Type the following custom procedure in the standard project module using a loop with a postcondition Until:

Sub summa()

Dim S As Integer

Dim i As Integer

S=0

i = 1

S = S + i^2

i = i + 1

Loop Until i > 10

MsgBox(S)

End Sub

There may be a situation where you need to execute a block of code multiple times. In general, statements are executed sequentially: the first statement in a function is executed first, then the second, etc.

Programming languages ​​provide different control structures that enable more complex execution paths.

The loop statement allows us to execute a statement or group of statements multiple times. Below is a general view of a loop statement in VBA.

VBA provides the following loop types to handle looping requirements. Click the following links to check their details.

for loop

A for loop is a repetition control structure that allows a developer to efficiently write a loop that needs to be executed a certain number of times.

Syntax

Below is the syntax of for loop in VBA.

For counter = start To end .... .... Next

Flow diagram

Below is the control flow in Loop mode -

  • The first step is completed. This step allows you to initialize any loop control variables and increment the step counter variable.
  • Secondly, the condition is evaluated. If true, the body of the loop is executed. If it is false, the body of the loop is not executed and control flow moves to the next statement immediately after the For loop.
  • After the For loop loop executes, control flow moves on to the next statement. This statement allows you to update any loop control variables. It is updated based on the step counter value.
  • The condition is now evaluated again. If true, the loop is executed and the process is repeated (loop body, then step increment, then condition again). Once the condition becomes false, the For loop ends.

example

Add a button and add the following function.

Private Sub Constant_demo_Click() Dim a As Integer a = 10 For i = 0 To a Step 2 MsgBox "The value is i is: " & i Next End Sub

When the above code is compiled and executed, it produces the following output.

The value is i is: 0
The value is i is: 2
The value is i is: 4
The value is i is: 6
The value is i is: 8
The value is i is: 10

Executes a sequence of statements multiple times and shortens the code that controls the loop variable.

for ... loop

Each loop is used to execute a statement or group of statements on each element in an array or collection.

For each loop is similar to For Loop; however, the loop is executed for each element in the array or group. Therefore, the step counter will not exist in this type of loop. It is mainly used with arrays or used in object context file system to work recursively.

Syntax

Below is the syntax of For Each loop in VBA.

For Each element In Group....Next

example

Private Sub Constant_demo_Click() "fruits is an array fruits = Array("apple", "orange", "cherries") Dim fruitnames As Variant "iterating using For each loop. For Each Item In fruits fruitnames = fruitnames & Item & Chr(10) Next MsgBox fruitnames End Sub

When the above code is executed, it prints all the names of the fruits with one element on each line.

apple
orange
cherries

This is executed if there is at least one element in the group and is repeated for each element in the group.

while..wend loop

In a While While ... Wend loop, if the condition is True, all statements are executed until the Wend keyword is encountered.

If the condition is false, the loop ends and the control moves to the next statement after the Wend keyword.

Syntax

Below is the syntax of While..Wend loop in VBA.

While condition(s) ... Wend

Flow diagram

example

Private Sub Constant_demo_Click() Dim Counter: Counter = 10 While Counter< 15 " Test value of Counter. Counter = Counter + 1 " Increment Counter. msgbox "The Current Value of the Counter is: " & Counter Wend " While loop exits if Counter Value becomes 15. End Sub

When the above code is executed, it will output the following in the message field.

The Current Value of the Counter is: 11
The Current Value of the Counter is: 12
The Current Value of the Counter is: 13
The Current Value of the Counter is: 14
The Current Value of the Counter is: 15

This checks the condition before executing the loop body.

do..while loop

A Do ... while loop is used when we want to repeat a set of statements while a condition is true. The condition can be checked at the beginning of the loop or at the end of the loop.

Syntax

Below is the syntax of Do...While loop in VBA.

Do While condition......Loop

Flow diagram

example

The following example uses a Do ... while loop to check the state at the beginning of the loop. The statements inside the loop are executed only if the condition becomes True.

Private Sub Constant_demo_Click() Do While i< 5 i = i + 1 msgbox "The value of i is: " & i Loop End Sub

The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
The value of i is: 5

Alternative syntax

There is also an alternative syntax for Do ... while loop that checks the state at the end of the loop. The main difference between these two syntaxes is explained in the following example.

Do ... ... Loop While condition

example

The following example uses a Do ... while loop to check the status at the end of the loop. Statements within a loop are executed at least once, even if the condition is False.

Private Sub Constant_demo_Click() i = 10 Do i = i + 1 MsgBox "The value of i is: " & i Loop While i< 3 "Condition is false.Hence loop is executed once. End Sub

When the above code is executed, it prints the following output in a message box.

The value of i is: 11

The do..While statements will be executed as long as the condition is True. (I.e.) The loop must be repeated until the condition is False.

do..intil loop

A do ... intil loop will not be used when we want to repeat a set of statements while the condition is false. The condition can be checked at the beginning of the loop or at the end of the loop.

Syntax

Below is the syntax of Do..Until loop in VBA.

Do Until condition ... ... Loop

Flow diagram

example

The following example uses Do... Before Loop to test a condition at the beginning of the loop. The statements inside the loop are executed only if the condition is false. It exits the loop when the condition becomes true.

Private Sub Constant_demo_Click() i = 10 Do Until i>15 "Condition is False.Hence loop will be executed i = i + 1 msgbox ("The value of i is: " & i) Loop End Sub

When the above code is executed, it prints the following output in a message box.

The value of i is: 11
The value of i is: 12
The value of i is: 13
The value of i is: 14
The value of i is: 15
The value of i is: 16

Alternative syntax

There is also an alternative syntax, Do... Before Loop, which tests the condition at the end of the loop. The main difference between these two syntaxes is explained by the following example.

Do ... ... Loop Until condition

Flow diagram

example

The following example uses Do...Before a loop to test a condition at the end of the loop. Statements within a loop are executed at least once, even if the condition is True.

Private Sub Constant_demo_Click() i = 10 Do i = i + 1 msgbox "The value of i is: " & i Loop Until i more15 "Condition is True.Hence loop is executed once. End Sub

When the above code is executed, it prints the following output in a message box.

The value of i is: 11

The do..Until statements will be executed as long as the condition is False. (I.e.) The loop must be repeated until the condition is true.

Cycle Control Records

Loop control statements change execution out of their normal sequence. When execution leaves scope, all other loop statements are not executed.

Control Statement and Description

Operator output

Exit for is used when we want to exit the For Loop based on certain criteria. When Exit For is executed, control moves to the next statement immediately after the For Loop.

Syntax

Below is the Exit For Statement syntax in VBA.

Flow diagram

example

The following example uses Exit For. If the counter reaches 4, the For Loop ends and control moves to the next statement immediately after the For Loop.

Private Sub Constant_demo_Click() Dim a As Integer a = 10 For i = 0 To a Step 2 "i is the counter variable and it is incremented by 2 MsgBox ("The value is i is: " & i) If i = 4 Then i = i * 10 "This is executed only if i=4 MsgBox ("The value is i is: " & i) Exit For "Exited when i=4 End If Next End Sub

When the above code is executed, it prints the following output in the message box.

The value is i is: 0
The value is i is: 2
The value is i is: 4
The value is i is: 40

Terminates a For loop statement and transfers execution to the statement immediately after the loop

Exit Do

Exit Do Statement is used when we want to exit Do Loops based on certain criteria. It can be used in both Do Do...While and Do...Before loops.

When Exit Do is executed, control passes to the next statement immediately after the Do Loop.

Syntax

Below is the syntax of Exit Do statement in VBA.

example

The following example uses Exit Do. If the counter reaches 10, the Do output line terminates and control passes to the next statement immediately after the For Loop.

Private Sub Constant_demo_Click() i = 0 Do While i<= 100 If i >10 Then Exit Do " Loop Exits if i>10 End If MsgBox ("The Value of i is: " & i) i = i + 2 Loop End Sub

When the above code is executed, it prints the following output in a message box.

The Value of i is: 0
The Value of i is: 2
The Value of i is: 4
The Value of i is: 6
The Value of i is: 8
The Value of i is: 10

Completes a Do While statement and transfers execution to the statement immediately after the loop

Laboratory work on programming basics

2.1. Tabulation of functions represented analytically
and converging nearby

Goal of the work

· Consolidation of theoretical knowledge on the basics of organizing branching and cyclic structures.

· Acquisition of practical programming skills using branching and cyclic structures in the Visual Basic system.

There are three types of loop statements in VB:

counting cycle: For...To...Next

loops with preconditions: Do While...Loop, Do Until...Loop, While...WEnd

· loops with postconditions: Do...Loop While, Do...Loop Until.

Counting loop – allows you to cycle through a set of statements a specified number of times. Its syntax is as follows:

For counter = Start To end

[operators]

[operators]

Next [ counter]

Parameter counter is a numeric variable (integer, real type or Date, Variant, Currency type) that is automatically incremented after each repetition. Initial value counter equal to parameter Start, and the final parameter – end. If not specified, the step is considered equal to 1; the step value can be changed. It can be a positive or negative number.

There are four syntactic constructs of the Do....Loop:

The statements between the keywords Do... Loop are executed a specified number of times depending on the condition. For example, in the following program fragment, when C = 100, the condition will be satisfied and the loop will be entered. Inside the loop, the procedure is called and the value of C is decreased by 1. Then the condition (C > 0) is checked again and the loop operators are executed again (they will be executed 100 times in total), until C = 0. When the condition C > 0 becomes false and the loop stops.

Do While C > 0

The same program fragment executed using a loop with a precondition in syntax 2:

In this case, the loop runs as long as the condition is False, unlike the previous case, that is, it continues before fulfillment of condition C = 0.

Loop statements 3 and 4 are very similar in syntax to the first two except that the condition Not is calculated until the loop is executed at least once.

These loop syntaxes can use the Exit For and Exit Do unconditional loop exit statements to transfer control to the operator behind the loop. For example, in the following program fragment, if the initial value of C is >50, then the loop will immediately stop.



Do Until C<= 0

MsgBox “Start” value is greater than acceptable”, “Input error”

The While...Wend loop was used in early versions of Visual Basic. Its syntax is as follows:

While<условие>

<Операторы>

Unlike the Do..Loop loop, the While ..Wend loop does not have a second option in which the condition is checked at the end of the loop. In addition, there is no loop exit statement for it, like Exit Do.

VBA. Organization of cycles.

Loop statements are used to repeat an action or group of actions a specified number of times. The number of repetitions (loop iterations) can be predefined or calculated.

VBA supports two types of looping constructs:

  1. Loops with a fixed number of repetitions ( countered loops).
  2. Loops with an indefinite number of repetitions ( conditional loops).

For all types of cycles the concept is used loop body , which defines a block of statements enclosed between the start and end statements of the loop. Each repetition of the execution of the statements of the body of the loop is called iteration

Fixed cycles

VBA provides two control structures for organizing a fixed loop: For ... Next (loop with a counter) and For Each ... Next (loop with an enumeration).

Operator For...Next This is a typical counter loop that executes a specified number of iterations. The syntax of the For...Next statement is:

For<счетчик> = <начЗначение>That<конЗначение>

<блок операторов>

Next [<счетчик>]

An example of using the For...Next operator.

Listing 1. For … Next operator

‘ TASK: Create a program that receives two numbers from the user.

‘ Adds all numbers in the range specified by these two numbers, and then

‘ displays the resulting amount.

Sub sample7()

Dim i As Integer ‘cycle counter

Dim sStart ‘initial counter value

Dim sEnd ‘end counter value

Dim sSum As Long ‘resulting sum

sStart = InputBox(“Enter the first number:”)

sEnd = InputBox(“Enter the second number:”)

sSum = 0

For i = CInt(sStart) To CInt(sEnd)

sSum = sSum + i

Next i

MsgBox “The sum of the numbers from “ & sStart & ” to “ & sEnd & ” is: “ & sSum

End Sub

Loop statement For Each...Nextbelongs to the category of object type operators, i.e. applies primarily to collections objects, as well as arrays . The body of the loop is executed a fixed number of times, corresponding to the number of elements in the array or collection. For Each...Next statement format:

For Each<элемент>In<группа> <блок операторов>Next [<элемент>]

Conditional loops (undefined loops)

Conditional loops are used when repeated actions need to be performed only under certain conditions. The number of iterations is not defined and in general can be equal to zero (in particular, for loops with a precondition). VBA offers developers several control structures for organizing conditional loops:

  • Four types of Do..Loops, which differ in the type of condition being checked and the time it takes to complete this check.
  • Continuous loop While... Wend.

The Do While... Loop is typical loop with precondition. The condition is checked before the body of the loop is executed. The cycle continues its work until it<условие>is executed (i.e. has the value True). Since the check is performed at the beginning, the body of the loop may never be executed. Do While... Loop Format:

Do While<условие>

<блок операторов>

Loop

Listing 2. Do While... Loop

‘ TASK: Create a program that requires user input

‘an arbitrary sequence of numbers. Input must be terminated

‘ only after the sum of the entered odd numbers exceeds 100.

Sub sample8()

Dim OddSum As Integer ‘sum of odd numbers

Dim OddStr As String ‘a string with odd numbers

Dim Num ‘to accept entered numbers

OddStr = “” ‘output string initialization

OddSum = 0 ‘initialize OddSum

Do While OddSum< 100 ‘начало цикла

Num = InputBox(“Enter a number: “)

If (Num Mod 2)<>0 Then ‘parity check

OddSum = OddSum + Num ‘accumulation of the sum of odd numbers

OddStr = OddStr & Num & ” ”

End If

Loop

‘print a string with odd numbers

MsgBox prompt:=”Odd numbers: ” & OddStr

End Sub

Do...Loop While Statementdesigned for organizationloop with postcondition. The condition is checked after the body of the loop has been executed at least once. The cycle continues its work until<условие>remains true. Do... Loop While Format:

Do<блок операторов>Loop While<условие>

Listing 3. Loop with postcondition

‘ TASK: Create a program for the game “Guess the number.” The program must be random

‘ way to generate a number in the range from 1 to 1000, the user must

‘ guess this number. The program displays a hint for each number entered

' "more or less".

Sub sample8()

Randomize Timer ‘initialize the random number generator

Dim msg As String ‘ message string

Dim SecretNumber As Long, UserNumber As Variant

Begin: SecretNumber = Round(Rnd * 1000) ‘ computer generated number

UserNumber = Empty ‘ number entered by the user

Do' gameplay

Select Case True

Case IsEmpty(UserNumber): msg = “Enter a number”

Case UserNumber > SecretNumber: msg = “Too many!”

Case UserNumber< SecretNumber: msg = “Слишком мало!”

End Select

UserNumber = InputBox(prompt:=msg, Title:=”Guess the number”)

Loop While UserNumber<>SecretNumber

' examination

If MsgBox(“Play again?”, vbYesNo + vbQuestion, “You guessed it!”) = vbYes Then

GoTo Begin

End If

End Sub

Loops Do Until... Loop and Do... Loop Until are inversions of the previously discussed conditional loops. In general, they work similarly, except that the body of the loop is executed if the condition is false (i.e.<условие>=False). Do Until... Loop Format:

Do Until<условие> <блок операторов>Loop

Do... Loop Until loop format:

<блок операторов>

Loop Until<условие>

Practical task:Rewrite the programs in Listings 10 and 11 using inverted loop statements.

Loop While...Wend also applies to conditional loops. This operator is fully consistent with the Do While... Loop structure. While...Wend loop format:

While<условие>

<блок операторов>

Wend

A distinctive feature of this operator is the impossibility forced termination(interrupting) the body of the loop (the Exit Do operator does not work in the While ... Wend loop).

Interrupting a cycle

To terminate an iteration early and exit the loop, the Exit statement is used. This operator is applicable in any cyclic structure except While... Wend. The general syntax for using Exit to break a loop is:

<начало_цикла>

[<блок операторов1>]

Exit (For | Do)

[<блок операторов2>]

<конец_цикла>

When the Exit statement is executed, the loop is interrupted and control is transferred to the statement following the statement<конец_цикла>. There may be several Exit statements in the body of a loop.

Listing 4. Force exit from loop

Sub sample9()

For i = 1 To 10000000

If i = 10 Then Exit For ‘ exit the loop when the counter reaches 10

Next




Top