Hardware and software setup

For next vba excel move to next. Loop statements in VBA

The loop instruction is an indication from which it is clear which set of instructions (this set of instructions is called the body of the loop) must be executed repeatedly and what is the rule for terminating the execution of the loop.

7.2.1. Parametric Loop For…Next

This loop is controlled by a parameter that, when the loop body is repeated, changes its value with a given step from a given initial value to a given final value. Such a cycle is used in the case when it is known in advance how many repetitions of the body execution must be performed.

Loop syntax: For CPI=NHCP To KZPC[ step CHIC] Loop body (one or more instructions) Next[CPI]

Words For(for), To(before), step(step), Next(then) are reserved.

Designations applied:

CPI – cycle parameter name (variable of any numeric type);

NZPC – the initial value of the cycle parameter (an expression of any numeric type), which the cycle parameter will have at the first execution of the cycle body;

KZPC is the final value of the cycle parameter (an expression of any numeric type), with which the current value of the cycle parameter is compared;

CHIC – step of changing the loop parameter (an expression of any numeric type) – an optional part of the loop instruction.

The numeric values ​​of NCPC and CDPC set the interval in which the cycle parameter will change. The optional SHICZ parameter specifies the step of changing the loop counter on each pass. By default, if it is absent, then it is taken equal to 1. Finally, after the instructions that make up the body of the loop, there follows a command denoting the boundary of the loop. In the case of nested loops (the loop body includes a loop statement), it is useful to indicate which of them the command belongs to. Next. This is achieved by adding after the word Next loop parameter name.

Instruction execution process ForNext for a positive step is illustrated in Figure 7.4.

Consider examples.

In the first example, we will write instructions for calculating the sum of all odd integers from 1 to 100.

Dim I As Integer, Sum As Integer

For i = 1 To 100 Step 2

Amount = Amount +i

The following example will demonstrate two possibilities: an explicit loop step and counting backwards. The latter is achieved by setting a negative step and by the fact that the initial value of the cycle parameter is greater than the final one.

Dim N As Integer

For N = 100 To 60 Step -10

This code will output on the current form:

The following instruction causes the computer to beep 50 times. Instruction For defines that the loop parameter is a variable x, its initial and final values. Command Next changes the counter in increments.

Dim x As Integer

instruction For...Next can be terminated early with the Exit For statement. Execution of this instruction results in an immediate exit from the loop.

7.2.2. Do While...Loop or Do...Loop While statement

Here While(for now) and loop(loop) reserved words. Type cycles While are intended for situations where the number of repetitions of the loop body (iterations) is not known in advance. Here is the syntax of the two varieties of loop While:

Do While ConditionRepetition Statement group loop

Do Instruction group loop while ConditionRepetitions

The difference between them lies in the fact that the Repetition Condition (the condition for repeating the execution of the loop body) is checked in the first case before the execution of the loop body (loop - while), and in the second case - after the execution of the loop body (loop - until).

Let's move on to examples.

Consider the action of the next section of the program.

Counter = 0

Do While Number > 10

Number = Number - 1

Counter = Counter + 1

MsgBox("Done" & Counter & _

" loop iterations.")

When this section of the program is executed, the following will be displayed in the MsgBox function window:

10 iterations of the loop have been completed.

In this program, the condition is checked before entering the loop. If the Number variable is set to 9 instead of 20, the statements inside the loop will not be executed.

In the following program, the statements inside the loop are executed only once before the condition is not met.

Counter = 0

Number = Number - 1

Counter = Counter + 1

Loop While Number > 10

MsgBox ("Done in loop " & Counter & _

"iterations.")

instruction Do...Loop can be completed ahead of schedule with instructions Exit Do.

Any actions of the procedure that are repeated a specified number of times or until a certain condition is met or not is called cycle .

The process of executing all statements enclosed in a loop structure once is called loop iteration.

Loop structures that always execute a given number of times are called loops with a fixed number of iterations. Other types of loop structures repeat a variable number of times depending on some set of conditions. Such cycles are called indefinite cycles.

The block of statements between the start and end of a loop is called "loop body".

The simplest loop structure is fixed cycle .

For..Next Loop

Syntax

For counter = Start To End
Statements
Next[ counter]

Counter - any numeric VBA variable
Start - any numeric expression, defines the initial value for the variable counter
End - numerical expression, defines the final value for the variable counter


By default VBA increments a variable counter by 1 each time the statements in the loop are executed. You can set another value ( SterSize- any numerical expression) to which will change counter.

Keyword Next tells VBA that the end of the loop has been reached. optional variable counter after keyword Next must be the same variable counter, which was given after the keyword For at the beginning of the loop structure.


Below is a listing of the simplest loop For..Next, which counts the sum of digits from 1 to 10:



And now two variants of the cycle For..Next using a loop step other than one:



Note! When decrementing the cycle counter For..Next the loop is executed while the counter variable is greater than or equal to the final value, and when the loop counter is incremented, the loop is executed while the counter variable is less than or equal to the final value.

For Each..Next Loop

Cycle For Each..Next does not use the cycle counter. Cycles For Each..Next are executed as many times as there are elements in a particular group, such as a collection of objects or an array (which will be discussed later). In other words, the cycle For Each..Next is executed once for each element in the group.

Syntax

For Each element In group
Statements
Next[ element]

Element - variable used to iterate over all elements in a specific group
Group is a collection object or an array
Statements - one, many, or none VBA statement(loop body).

Loops allow you to execute one or more lines of code multiple times. VBA supports the following loops:

For...Next For Each...Next Do... Loop

The For construct. . . next. When the number of repetitions is known in advance, a For loop is used. . . next. The For loop uses a variable called a loop variable or loop counter that increments or decrements by a given amount each time the loop repeats. The syntax for this construct is:

For counter = start To end Next statements

The parameters counter (counter), start (cycle start), end (cycle end) and increment (increment) are numeric.

Note. The increment parameter can be either positive or negative. If it is positive, the start parameter must be less than or equal to the end parameter, otherwise the loop will not run. If the increment parameter is negative, then the start parameter must be greater than or equal to the value of the end parameter in order to execute the body of the loop. If the Step parameter is not set, then the default value of the increment parameter is 1.

VBA executes the For loop in the following sequence:

1. Sets the loop variable counter to start.

2. Compares the value of the loop variable counter and the value of the end parameter. If the counter variable is greater, VBA terminates the loop. (If the value of the increment parameter is negative, then VBA terminates the loop if the value of the loop variable counter is less than the value of the end parameter.)

3. Executes the statements of the loop body statements.

4. Increases the value of the loop variable counter by 1, or by the value of the increment parameter, if one is given.

5. Repeat steps 2 to 4.

Consider an example: Calculate the value of the function f(t)

given a, b, n, if t changes from a to b in increments of Dt=(b-a)/(n-1).

Sub example3() Dim f() As Single Dim a As Single, b As Single, t As Single, dt As Single Dim i As Integer, n As Integer Call read("a1", a) : Call read("b1" , b) : Call read("c1", n) ReDim f(1 To n - 1) dt = (b - a) / (n - 1) : t = a Call out("a2", "i") : Call out("b2", "t") : Call out("c2", "f(t)") For i = 1 To n - 1 t = t + dt If t<= -1 Then f(i) = -1 ElseIf t >1 Then f(i) = 1 Else f(i) = t End If Call out("a" & (2 + i), i) : Call out("b" & (2 + i), t) : Call out("c" & (2 + i), f(i)) Next i End Sub

The For Each construct. . . Next

For Each loop. . . Next is like a For loop. . . Next, but it repeats a group of statements for each element from a set of objects or from an array, instead of repeating the statements a given number of times. It is especially useful when you don't know how many elements are in the set.

Construction syntax For loop each. . . Next is:

For Each element In group statements Next element

Be aware of the following restrictions when using a For Each loop. . . Next:

For sets, the element parameter can only be type variable variant, a shared variable of type object, or an object listed in the Object Browser

For arrays, the element parameter can only be a variable of type Variant

You cannot use a For Each loop. . . Next with an array of user-defined type because a variable of type variant cannot contain a value of user-defined type

Do...Loop design

The Do loop is used to execute a block of statements an unlimited number of times. There are several variations of the Do construct. . . Loop, but each of them evaluates a conditional expression to determine when to exit the loop. As in the case of the If construct. . . Then the condition must be a value or an expression that takes False value(zero) or True (not null).

In the following construction, Do . . . Loop statements are executed as long as the value of the condition is True (True):

Do While Condition Loop Statements

When executing this loop, VBA first checks the condition. If the condition is False, it skips all loop statements. If it is True, VBA executes the loop statements, returns to the Do While statement again, and tests the condition again.

Therefore, the loop represented by this construct can be executed any number of times as long as the condition value is not zero or True. Note that the statements of the loop body are never executed if the first time the condition is checked, it turns out to be false (False).

Consider an example: Calculate the sum of a series

with a given accuracy.

Sub example4() Dim e As Single, x As Single, s As Single Dim m As Single, p As Single, i As Single Call read("a1", x) : Call read("b1", e) s = 0 : i = 1: m = 1: p = -1 Call out("a2", "i") : Call out("b2", "m") : Call out("c2", "s") Do While Abs(m) >= ep = -p * xm = p / is = s + m Call out("a" & (2 + i), i) : Call out("b" & (2 + i), Abs (m)) : Call out("c" & (2 + i), s) i = i + 1 Loop End Sub

Another variation of the Do construct. . . Loop first executes the statements of the body of the loop, and then checks the condition after each execution. This variation ensures that the statements in the loop body are executed at least once:

Do statements Loop While condition

The other two varieties of the loop construct are similar to the previous ones, except that the loop is executed while the condition is false (False):

The loop is not executed at all or is executed many times:

Do until condition

Loop statements

The loop is executed at least once:

operators

Loop Until condition

7.2 Nested loops.

You can put control structures inside other control structures (for example, an If . . . Then block inside a For . . . Next loop). A control structure placed inside another control structure is said to be nested.

The depth of nesting of control structures in VBA is not limited. To improve the readability of the code, it is common practice to shift the body of a decision construct or loop in the program when nested control structures are used.

When nesting one or more other loops in a loop, one speaks of nested loops, which distinguish between outer (enclosing) and inner (nested) loops.

Consider an example of summing the elements Aij of the matrix A(n,m) row by row.

Sub example5() Dim a() As Single, s() As Single Dim n As Integer, m As Integer Dim i As Integer, j As Integer Call read("a1", n): Call read("b1", m ) ReDim a(1 To n, 1 To m), s(1 To n) "Read matrix For i = 1 To n For j = 1 To m Call readcell(i + 1, j, a(i, j)) Next j Next i "Calculation For i = 1 To ns(i) = 0 For j = 1 To ms(i) = s(i) + a(i, j) Next j Call outcell(i + 1, m + 1 , s(i)) Next i End Sub

Note that the first Next closes the inner For loop, and the last Next closes the outer For loop. Similarly, for nested If statements, End If statements are automatically applied to close the nearest If statement. Nested structures Do . . . Loops work in a similar way: the farthest Loop statement corresponds to the farthest Do statement.

When input/output of elements of a two-dimensional array on a worksheet Microsoft Excel it is convenient to apply custom I / O procedures:

Sub readcell(i As Integer, j As Integer, val As Variant) val = Leaf1.Cells(i, j).Value End Sub Sub outcell(i As Integer, j As Integer, val As Variant) Leaf1.Cells(i, j).Value = val End Sub

where I is the row number, j is the worksheet column number.

Leaving control structures

The Exit statement allows you to exit directly from a For loop, a Do loop, a Sub procedure, or a Function procedure. Syntax Exit statement simple:

For counter = start To end [statement block] [statement block] Next Do [(While | Until) condition] [statement block] [statement block] Loop

Exit For inside a For loop and Exit Do inside a Do loop can appear any number of times.

The Exit Do statement works with all variations of the Do loop syntax.

The Exit For and Exit Do statements are used when it is necessary to end the loop immediately, without continuing further iterations or without waiting for the execution of a block of statements in the loop body.

When you use the Exit statement to exit a loop, the values ​​of the loop variable depend on how the loop terminates:

When the loop terminates normally, the value of the loop variable is one more than the upper bound on the number of loops

When the loop terminates prematurely, the loop variable retains its value, which it received, taking into account the usual rules

When the loop terminates at the end of the set, the loop variable is Nothing if it is an object variable, or Empty if it is a Variant

A cycle is an algorithmic structure, with the help of which multiple repetition of a block of statements is implemented.

Loop statement with counter (For … Next)

The For … Next statement allows you to loop through a set of instructions (statements) a specified number of times. Instruction syntax:

For counter = start_value To end_value

[instructions]

[instructions]

Next[ counter]

Parameter counter is a numeric variable that automatically changes its value by the value step after each iteration of the cycle. The cycle is executed until counter£ end_value with a positive value of the parameter step or until counter³ end_value with a negative value of the parameter step. Thus, the loop will never be executed if, with a positive step value start_value more than end_value. If the Step parameter step is omitted, then by default the increment of the counter variable is set to 1.

The Exit For statement terminates the execution of the loop "early" and transfers control to the statement following the loop statement. Exit For is usually placed in a conditional statement, for example:

If condition Then Exit For

Note. According to the syntax of the For statement, the parameter counter is an arithmetic variable of any type, it is still better to use whole type variable, because fractional part the value of a variable of real type usually has an error. It has to do with the way numbers are stored in a computer.

Example 1

Find the sum of the first 10 natural numbers: S = 1 + 2 + 3 + ...+ 10 . Program fragment:

Dim I as Integer, S as Integer

S=0 " Zeroing the value of the variable S

For i = 1 to 10 " Beginning of the cycle. Set start and end values
"loop parameter. The default loop step is 1.

S = S + i " The assignment operator is executed every time
"execution of the cycle, in this example 10 times

Next I " End of cycle. The value of the cycle parameter is incremented.

In this program fragment, the loop will be executed exactly 10 times.

Example 2

Display in the 1st column of the worksheet (starting from the 2nd row) x values ​​in the range from 0 to 3.2 with a step of 0.4.

Public Sub Tab()

Dim x As Single, i As Integer

For x = 0 To 3.2 Step 0.4

Although the length of the interval is exactly divisible by the step 0.4, the result on the worksheet is:

What to do?

1. You can slightly increase the final value, in this example, instead of 3.2, write 3.201.

2. Determine the number of repetitions of the chicle and write a loop over an integer type counter.

In this case, the program will look like:

Public Sub Tab1()

Dim x As Single, i As Integer, n As Integer

n = CInt((3.2 - 0) / 0.4)

For i = 0 To n Step 1

Cells(i + 2, 1) = x

For Each … Next Loop Statement

The For Each … Next loop allows you to repeat the execution of a group of statements for each element of an array or family. This instruction has the following syntax:

For Each element In Group

[instructions]

[instructions]

Next[ element]

Parameter element is a variable that represents an element of a family or array. Argument Group is the name of the array or family. The statements are executed only once for each member of the group. Using the statement is convenient because you don't need to know in advance how many elements are in an array or family. Variable element must be of type Variant.

Example 1

Find the arithmetic mean of all elements of the selected range

Public Function Mean(Range As Range) As Double

Dim Element As Variant

Dim Sum As Double

Dim Number As Integer

Quantity = 0

For Each Element In Range

Amount = Amount + Item

Quantity = Quantity + 1

Next Element

Average = Amount / Quantity

Application. The selected range of adjacent cells must contain numbers. Numbers in empty cells are considered 0. Text in the cell will result in an error.

The If … End If, Select … Case, For … Next, For Each … Next statements listed above are a group of control statements that change the order in which commands are executed. Control instructions can be nested in any order.

In addition to decision-making structures, there is another type of control structure called a cycle.

Cycle- this is an algorithmic structure, with the help of which multiple repetition of blocks of statements is implemented.

IN Visual language Basic, there are three main types of loops, which are implemented using the For:Next, Do:Loop, and While:Wend constructs.

For:Next loop. It is used when the number of repetitions of a given block of statements is known in advance. This design looks like this:

For counter = start value To end value Statements1 Statements2 Next [counter]

When the above statements are executed for the first time, the counter variable is assigned an initial value, after which two options are possible. If, as a result of checking the condition counter > final value, the value True was obtained, then the loop is terminated, while the statement1 and statement2 blocks are never executed. On the other hand, if the result of the condition test is False, then in this case the statement blocks are executed for the first time, after which the transition to the beginning of the loop occurs. Next, the value of the counter variable is incremented by the step located after the Step keyword (if it is absent, step = 1 is set). After that, the truth of the condition counter > final value, etc. is checked again, the loop ends at the moment when the result of this check becomes True.

It is often necessary to "abort" the loop when some additional condition is met. In this case, inside the loop, you should use the service phrase Exit:For, which is usually located in the control structure, for example:

If condition Then Exit For

If the result of the condition test is True, then the execution of the loop will be terminated, and the statement1 block will be executed again, and the statement2 block will not.

Do:Loop. It is used when the number of repetitions of the loop body statements is not known in advance. There are four variations of this design. When using the first two, the loop will either run many times or not run at all.

Do Until Condition Loop Statements

If the result of the condition check is False, then the block statements are executed, otherwise the transition to the statement located after the service word Loop is performed. On the other hand, if the first test of the condition evaluates to True, then the loop will never be executed.

Do While condition Loop statements

If the condition is true, then the statement block is executed; if it is false, that is, the result of the check is False, then the loop will not be executed even once.

If the last two constructs are used, the loop will be executed at least once.

Do Statements Loop Until condition

The block statements are executed as long as the result of the condition test is False, otherwise the loop ends.

Do Statements Loop While condition

If the condition is false, the block statements are executed; if it is true, i.e. the result of the check is True, then the end of the chicle occurs.

While:Wend loop. It is also used when the number of repetitions of the statements of the loop body is not known in advance, and has the following syntax:

While condition Wend statements

If the result of the condition check is True, then the statement block is executed, otherwise the transition to the statement located after the service word Wend is performed. On the other hand, if the first test of the condition evaluates to False, then the loop will never be executed.

Liked the article? Share with friends!
Was this article helpful?
Yes
Not
Thanks for your feedback!
Something went wrong and your vote was not counted.
Thanks. Your message has been sent
Did you find an error in the text?
Select it, click Ctrl+Enter and we'll fix it!