Примеры цикл в цикле vba excel

In this Article

  • VBA Loop Quick Examples
    • For Each Loops
    • For Next Loops
    • Do While Loops
    • Do Until Loops
  • VBA Loop Builder
  • VBA For Next Loop
    • For Loop Syntax
    • For Loop Step
    • For Loop Step – Inverse
    • Nested For Loop
    • Exit For
    • Continue For
  • VBA For Each Loop
    • For Each Cell in Range
    • For Each Worksheet in Workbook
    • For Each Open Workbook
    • For Each Shape in Worksheet
    • For Each Shape in Each Worksheet in Workbook
    • For Each – IF Loop
  • VBA Do While Loop
    • Do While
    • Loop While
  • VBA Do Until Loop
    • Do Until
    • Loop Until
  • Exit Do Loop
  • End or Break Loop
  • More Loop Examples
    • Loop Through Rows
    • Loop Through Columns
    • Loop Through Files in a Folder
    • Loop Through Array
  • Loops in Access VBA

To work effectively in VBA, you must understand Loops.

Loops allow you to repeat a code block a set number of times or repeat a code block on a each object in a set of objects.

First we will show you a few examples to show you what loops are capable of. Then we will teach you everything about loops.

VBA Loop Quick Examples

For Each Loops

For Each Loops loop through every object in a collection, such as every worksheet in workbook or every cell in a range.

Loop Through all Worksheets in Workbook

This code will loop through all worksheets in the workbook, unhiding each sheet:

Sub LoopThroughSheets()
Dim ws As Worksheet
 
    For Each ws In Worksheets
        ws.Visible = True
    Next
 
End Sub

Loop Through All Cells in Range

This code will loop through a range of cells, testing if the cell value is negative, positive, or zero:

Sub If_Loop()
Dim Cell as Range
 
  For Each Cell In Range("A2:A6")
    If Cell.Value > 0 Then
      Cell.Offset(0, 1).Value = "Positive"
    ElseIf Cell.Value < 0 Then
      Cell.Offset(0, 1).Value = "Negative"
    Else
      Cell.Offset(0, 1).Value = "Zero"
     End If
  Next Cell
 
End Sub

vba else if statement

For Next Loops

Another type of “For” Loop is the For Next Loop.  The For Next Loop allows you to loop through integers.

This code will loop through integers 1 through 10, displaying each with a message box:

Sub ForLoop()
    Dim i As Integer
    For i = 1 To 10
        MsgBox i
    Next i
End Sub

Do While Loops

Do While Loops will loop while a condition is met. This code will also loop through integers 1 through 10, displaying each with a message box.

Sub DoWhileLoop()
    Dim n As Integer
    n = 1
    Do While n < 11
        MsgBox n
        n = n + 1
    Loop
End Sub

Do Until Loops

Conversely, Do Until Loops will loop until a condition is met. This code does the same thing as the previous two examples.

Sub DoUntilLoop()
    Dim n As Integer
    n = 1
    Do Until n >= 10
        MsgBox n
        n = n + 1
    Loop
End Sub

We will discuss this below, but you need to be extremely careful when creating Do While or Do Until loops so that you don’t create a never ending loop.

VBA Loop Builder

vba loop builder

This is a screenshot of the “Loop Builder” from our Premium VBA Add-in: AutoMacro. The Loop Builder allows you to quickly and easily build loops to loop through different objects, or numbers. You can perform actions on each object and/or select only objects that meet certain criteria.

The add-in also contains many other code builders, an extensive VBA code library, and an assortment of coding tools. It’s a must have for any VBA developer.

Now we will cover the different types of loops in depth.

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!

automacro

Learn More

VBA For Next Loop

For Loop Syntax

The For Next Loop allows you to repeat a block of code a specified number of times. The syntax is:

[Dim Counter as Integer]

For Counter = Start to End [Step Value]
    [Do Something]
Next [Counter]

Where the items in brackets are optional.

  • [Dim Counter as Long] – Declares the counter variable. Required if Option Explicit is declared at the top of your module.
  • Counter – An integer variable used to count
  • Start – The start value (Ex. 1)
  • End – The end value (Ex. 10)
  • [Step Value] – Allows you to count every n integers instead of every 1 integer. You can also go in reverse with a negative value (ex. Step -1)
  • [Do Something] – The code that will repeat
  • Next [Counter] – Closing statement to the For Next Loop. You can include the Counter or not. However, I strongly recommend including the counter as it makes your code easier to read.

If that’s confusing, don’t worry. We will review some examples:

Count to 10

This code will count to 10 using a For-Next Loop:

Sub ForEach_CountTo10()

Dim n As Integer
For n = 1 To 10
    MsgBox n
Next n

End Sub

For Loop Step

Count to 10 – Only Even Numbers

This code will count to 10 only counting even numbers:

Sub ForEach_CountTo10_Even()

Dim n As Integer
For n = 2 To 10 Step 2
    MsgBox n
Next n

End Sub

Notice we added “Step 2”. This tells the For Loop to “step” through the counter by 2.  We can also use a negative step value to step in reverse:

VBA Programming | Code Generator does work for you!

For Loop Step – Inverse

Countdown from 10

This code will countdown from 10:

Sub ForEach_Countdown_Inverse()

Dim n As Integer
For n = 10 To 1 Step -1
    MsgBox n
Next n
MsgBox "Lift Off"

End Sub

Delete Rows if Cell is Blank

I’ve most frequently used a negative step For-Loop to loop through ranges of cells, deleting rows that meet certain criteria.  If you loop from the top rows to the bottom rows, as you delete rows you will mess up your counter.

This example will delete rows with blank cells (starting from the bottom row):

Sub ForEach_DeleteRows_BlankCells()

Dim n As Integer
For n = 10 To 1 Step -1
    If Range("a" & n).Value = "" Then
        Range("a" & n).EntireRow.Delete
    End If
Next n

End Sub

Nested For Loop

You can “nest” one For Loop inside another For Loop. We will use Nested For Loops to create a multiplication table:

Sub Nested_ForEach_MultiplicationTable()

Dim row As Integer, col As Integer

For row = 1 To 9
    For col = 1 To 9
        Cells(row + 1, col + 1).Value = row * col
    Next col
Next row

End Sub

vba nested for loop

Exit For

The Exit For statement allows you to exit a For Next loop immediately.

You would usually use Exit For along with an If Statement, exiting the For Next Loop if a certain condition is met.

For example, you might use a For Loop to find a cell. Once that cell is found, you can exit the loop to speed up your code.

This code will loop through rows 1 to 1000, looking for “error” in column A. If it’s found, the code will select the cell, alert you to the found error, and exit the loop:

Sub ExitFor_Loop()

Dim i As Integer
 
For i = 1 To 1000
    If Range("A" & i).Value = "error" Then
        Range("A" & i).Select
        MsgBox "Error Found"
        Exit For
    End If
Next i

End Sub

Important: In the case of Nested For Loops, Exit For only exits the current For Loop, not all active Loops.

Continue For

VBA does not have the “Continue” command that’s found in Visual Basic. Instead, you will need to use “Exit”.

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

VBA For Each Loop

The VBA For Each Loop will loop through all objects in a collection:

  • All cells in a range
  • All worksheets in a workbook
  • All shapes in a worksheet
  • All open workbooks

You can also use Nested For Each Loops to:

  • All cells in a range on all worksheets
  • All shapes on all worksheets
  • All sheets in all open workbooks
  • and so on…

The syntax is:

For Each Object in Collection
[Do Something]
Next [Object]

Where:

  • Object – Variable representing a Range, Worksheet, Workbook, Shape, etc. (ex. rng)
  • Collection – Collection of objects (ex. Range(“a1:a10”)
  • [Do Something] – Code block to run on each object
  • Next [Object] – Closing statement. [Object] is optional, however strongly recommended.

For Each Cell in Range

This code will loop through each cell in a range:

Sub ForEachCell_inRange()

Dim cell As Range

For Each cell In Range("a1:a10")
    cell.Value = cell.Offset(0,1).Value
Next cell

End Sub

For Each Worksheet in Workbook

This code will loop through all worksheets in a workbook, unprotecting each sheet:

Sub ForEachSheet_inWorkbook()

Dim ws As Worksheet

For Each ws In Worksheets
    ws.Unprotect "password"
Next ws

End Sub

For Each Open Workbook

This code will save and close all open workbooks:

Sub ForEachWB_inWorkbooks()

Dim wb As Workbook

For Each wb In Workbooks
    wb.Close SaveChanges:=True
Next wb

End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

For Each Shape in Worksheet

This code will delete all shapes in the active sheet.

Sub ForEachShape()

Dim shp As Shape

For Each shp In ActiveSheet.Shapes
    shp.Delete
Next shp

End Sub

For Each Shape in Each Worksheet in Workbook

You can also nest For Each Loops. Here we will loop through all shapes in all worksheets in the active workbook:

Sub ForEachShape_inAllWorksheets()

Dim shp As Shape, ws As Worksheet

For Each ws In Worksheets
    For Each shp In ws.Shapes
        shp.Delete
    Next shp
Next ws

End Sub

For Each – IF Loop

As we’ve mentioned before, you can use an If statement within a loop, performing actions only if certain criteria is met.

This code will hide all blank rows in a range:

Sub ForEachCell_inRange()

Dim cell As Range

For Each cell In Range("a1:a10")
    If cell.Value = "" Then _
       cell.EntireRow.Hidden = True
Next cell

End Sub

VBA Do While Loop

The VBA Do While and Do Until (see next section) are very similar. They will repeat a loop while (or until) a condition is met.

The Do While Loop will repeat a loop while a condition is met.

Here is the Do While Syntax:

Do While Condition
[Do Something]
Loop

Where:

  • Condition – The condition to test
  • [Do Something] – The code block to repeat

You can also set up a Do While loop with the Condition at the end of the loop:

Do 
[Do Something]
Loop While Condition

We will demo each one and show how they differ:

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Do While

Here is the Do While loop example we demonstrated previously:

Sub DoWhileLoop()
    Dim n As Integer
    n = 1
    Do While n < 11
        MsgBox n
        n = n + 1
    Loop
End Sub

Loop While

Now let’s run the same procedure, except we will move the condition to the end of the loop:

Sub DoLoopWhile()
    Dim n As Integer
    n = 1
    Do
        MsgBox n
        n = n + 1
    Loop While n < 11
End Sub

VBA Do Until Loop

Do Until Loops will repeat a loop until a certain condition is met. The syntax is essentially the same as the Do While loops:

Do Until Condition
[Do Something]
Loop

and similarly the condition can go at the start or the end of the loop:

Do 
[Do Something]
Loop Until Condition

Do Until

This do Until loop will count to 10, like our previous examples

Sub DoUntilLoop()
    Dim n As Integer
    n = 1
    Do Until n > 10
        MsgBox n
        n = n + 1
    Loop
End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Loop Until

This Loop Until loop will count to 10:

Sub DoLoopUntil()
    Dim n As Integer
    n = 1
    Do
        MsgBox n
        n = n + 1
    Loop Until n > 10
End Sub

Exit Do Loop

Similar to using Exit For to exit a For Loop, you use the Exit Do command to exit a Do Loop immediately

Exit Do

Here is an example of Exit Do:

Sub ExitDo_Loop()

Dim i As Integer
i = 1 

Do Until i > 1000
    If Range("A" & i).Value = "error" Then
        Range("A" & i).Select
        MsgBox "Error Found"
        Exit Do
    End If
    i = i + 1
Loop

End Sub

End or Break Loop

As we mentioned above, you can use the Exit For or Exit Do to exit loops:

Exit For
Exit Do

However, these commands must be added to your code before you run your loop.

If you are trying to “break” a loop that’s currently running, you can try pressing ESC or CTRL + Pause Break on the keyboard. However, this may not work.  If it doesn’t work, you’ll need to wait for your loop to end or, in the case of an endless loop, use CTRL + ALT + Delete to force close Excel.

This is why I try to avoid Do loops, it’s easier to accidentally create an endless loop forcing you to restart Excel, potentially losing your work.

More Loop Examples

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Loop Through Rows

This will loop through all the rows in a column:

Public Sub LoopThroughRows()
 
Dim cell As Range
 
For Each cell In Range("A:A")
    If cell.value <> "" Then MsgBox cell.address & ": " & cell.Value
Next cell
 
End Sub

Loop Through Columns

This will loop through all columns in a row:

Public Sub LoopThroughColumns()

Dim cell As Range

For Each cell In Range("1:1")
    If cell.Value <> "" Then MsgBox cell.Address & ": " & cell.Value
Next cell

End Sub

Loop Through Files in a Folder

This code will loop through all files in a folder, creating a list:

Sub LoopThroughFiles ()

Dim oFSO As Object
Dim oFolder As Object
Dim oFile As Object
Dim i As Integer

Set oFSO = CreateObject("Scripting.FileSystemObject")

Set oFolder = oFSO.GetFolder("C:Demo)

i = 2

For Each oFile In oFolder.Files
    Range("A" & i).value = oFile.Name
    i = i + 1
Next oFile

End Sub

Loop Through Array

This code will loop through the array ‘arrList’:

For i = LBound(arrList) To UBound(arrList)
    MsgBox arrList(i)
Next i

The LBound function gets the “lower bound” of the array and UBound gets the “upper bound”.

Loops in Access VBA

Most of the examples above will also work in Access VBA. However, in Access, we loop through the Recordset Object rather than the Range Object.

Sub LoopThroughRecords()
   On Error Resume Next
   Dim dbs As Database
   Dim rst As Recordset
   Set dbs = CurrentDb
   Set rst = dbs.OpenRecordset("tblClients", dbOpenDynaset)
   With rst
      .MoveLast
      .MoveFirst
      Do Until .EOF = True
         MsgBox (rst.Fields("ClientName"))
        .MoveNext
     Loop
   End With
   rst.Close
   Set rst = Nothing
   Set dbs = Nothing
End Sub

7.1 Операторы цикла
7.2 Вложенные циклы


7.1 Операторы цикла.

Циклы позволяют выполнить одну или несколько строк кода несколько раз. VBA поддерживает следующие циклы:

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

Конструкция For . . . Next. Когда число повторений известно заранее, используют цикл For . . . Next. В цикле For используется переменная, называемая переменной цикла или счетчиком цикла, которая увеличивается или уменьшается на заданную величину при каждом повторении цикла. Синтаксис этой конструкции следующий:

For counter = start To end [Step increment]
 операторы 
Next [counter]

Параметры counter (счетчик), start (начало цикла), end (конец цикла) и increment (приращение) являются числовыми.

Примечание. Параметр increment может быть как положительным, так и отрицательным. Если он положителен, параметр start должен быть меньше или равен параметру end, иначе цикл не будет выполняться. Если параметр increment отрицателен, то параметр start должен быть больше или равен значению параметра end, чтобы выполнялось тело цикла. Если параметр Step не задан, то значение параметра increment по умолчанию равно 1.

VBA выполняет цикл For в следующей последовательности:

1. Устанавливает значение переменной цикла counter в значение start.

2. Сравнивает значение переменной цикла counter и значение параметра end. Если переменная counter больше, VBA завершает выполнение цикла. (Если значение параметра increment отрицательно, то VBA прекращает выполнение цикла при условии, что значение переменной цикла counter меньше значения параметра end.)

3. Выполняет операторы тела цикла statements.

4. Увеличивает значение переменной цикла counter на 1 или на величину значения параметра increment, если он задан.

5. Повторяет шаги со 2 по 4.

Рассмотрим пример: Вычислить значение функции f(t)

при заданных a, b, n, если t изменяется от a до b с шагом Dt=(b-a)/(n-1).

Sub пример3()
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

Конструкция For Each . . . Next

Цикл For Each . . . Next похож на цикл For . . . Next, но он повторяет группу операторов для каждого элемента из набора объектов или из массива, вместо повторения операторов заданное число раз. Он особенно полезен, когда неизвестно, сколько элементов содержится в наборе.

Синтаксис конструкции цикла For Each . . . Next таков:

For Each element In group
  операторы 
Next element

Следует помнить следующие ограничения при использовании цикла For Each . . . Next:

 Для наборов параметр element может быть только переменной типа variant, общей переменной типа object или объектом, перечисленным в Object Browser

 Для массивов параметр element может быть только переменной типа Variant

 Нельзя использовать цикл For Each . . . Next с массивом, имеющим определенный пользователем тип, так как переменная типа variant не может содержать значение определенного пользователем типа

Конструкция Do…Loop

Цикл Do применяется для выполнения блока операторов неограниченное число раз. Существует несколько разновидностей конструкции Do . . . Loop, но каждая из них вычисляет выражение-условие, чтобы определить момент выхода из цикла. Как и в случае конструкции If . . . Then условие должно быть величиной или выражением, принимающими значение False (нуль) или True (не нуль).

В следующей конструкции Do . . . Loop операторы выполняются до тех пор, пока значением условия является True (Истина):

Do While условие
  операторы 
Loop

Выполняя этот цикл, VBA сначала проверяет условие. Если условие ложно (False), он пропускает все операторы цикла. Если оно истинно (True), VBA выполняет операторы цикла, снова возвращается к оператору Do While и снова проверяет условие.

Следовательно, цикл, представленный данной конструкцией, может выполняться любое число раз, пока значением условия является не нуль или True (Истина). Отметим, что операторы тела цикла не выполняются ни разу, если при первой проверке условия оно оказывается ложным (False).

Рассмотрим пример: Вычислить сумму ряда

с заданной точностью.

Sub пример4()
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) >= e
p = -p * x
m = p / i
s = 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

Другая разновидность конструкции Do . . . Loop сначала выполняет операторы тела цикла, а затем проверяет условие после каждого выполнения. Эта разновидность гарантирует, что операторы тела цикла выполнятся по крайней мере один раз:

Do
  операторы 
Loop 
While условие

Две другие разновидности конструкции цикла аналогичны предыдущим, за исключением того, что цикл выполняется, пока условие ложно (False):

 Цикл не выполняется вообще или выполняется много раз:

Do Until условие

операторы Loop

 Цикл выполняется по крайней мере один раз:

Do

операторы

Loop Until условие

7.2 Вложенные циклы.

Можно помещать структуры управления внутрь других структур управления (например, блок If . . . Then внутрь цикла For . . . Next). Говорят, что структура управления, помещенная внутрь другой структуры управления, является вложенной.

Глубина вложения управляющих структур в VBA не ограничена. Для улучшения читаемости кода принята практика смещения тела конструкции принятия решения или цикла в программе в случае использования вложенных структур управления.

При вложении в цикл одного или несколько других циклов говорят о вложенных циклах, в которых различают внешние (охватывающие) и внутренние (вложенные) циклы.

Рассмотрим пример суммирования элементов Aij матрицы A(n,m) построчно.

Sub пример5()
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)
'Чтение матрицы
For i = 1 To n
For j = 1 To m
Call readcell(i + 1, j, a(i, j))
Next j
Next i
'Вычисление
For i = 1 To n
s(i) = 0
For j = 1 To m
s(i) = s(i) + a(i, j)
Next j
Call outcell(i + 1, m + 1, s(i))
Next i
End Sub

Заметим, что первый оператор Next закрывает внутренний цикл For, а последний оператор Next закрывает внешний цикл For. Точно так же и для вложенных операторов If, операторы End If автоматически применяются для закрытия ближайшего к нему оператора If. Вложенные структуры Do . . . Loop работают подобным же образом: самый дальний оператор Loop соответствует самому дальнему оператору Do.

При вводе/выводе элементов двумерного массива на рабочий лист Microsoft Excel удобно применять пользовательские процедуры ввода/вывода:

Sub readcell(i As Integer, j As Integer, val As Variant)
val = Лист1.Cells(i, j).Value
End Sub
Sub outcell(i As Integer, j As Integer, val As Variant)
Лист1.Cells(i, j).Value = val
End Sub

где I — номер строки, j — номер столбца рабочего листа.

Выход из структур управления

Оператор Exit позволяет выходить непосредственно из цикла For, цикла Do, процедуры Sub или процедуры Function. Синтаксис оператора Exit прост:

For counter = start To end [Step -increment]
[блок операторов]
[Exit For]
[блок операторов] 
Next [counter]
Do [(While | Until} условие]
[блок операторов]
[Exit Do]
[блок операторов] 
Loop

Exit For внутри цикла For и Exit Do внутри цикла Do могут появиться сколько угодно раз.

Оператор Exit Do работает со всеми разновидностями синтаксиса цикла Do.

Операторы Exit For и Exit Do применяются, если необходимо завершить цикл немедленно, не продолжая дальнейших итераций или не ожидая выполнения блока операторов в теле цикла.

При использовании оператора Exit для выхода из цикла значения переменной цикла зависят от того, каким образом завершается выполнение цикла:

 При нормальном завершении цикла значение переменной цикла имеет на единицу больше верхней границы числа циклов

 При преждевременном завершении цикла переменная цикла сохраняет свое значение, которое она получила с учетом обычных правил

 При завершении цикла по концу набора переменная цикла имеет значение Nothing (Ничего), если она является переменной типа object (Объект), или значение Empty (Пусто), если она является переменной типа Variant

Циклы в VBA Excel предназначены для повторения одного и того же блока операторов. Количество итераций может быть задано явно, зависеть от условия или количества элементов, содержащихся в обрабатываемом объекте.

Цикл For… Next

Цикл For… Next в VBA Excel предназначен для выполнения группы операторов необходимое количество раз, заданное счетчиком — специальной переменной цикла. После выполнения каждой итерации значение счетчика увеличивается или уменьшается на единицу или на число, указанное с помощью оператора Step. Предусмотрен принудительный выход из цикла с помощью оператора Exit For. Перейти к подробному описанию …

Цикл Do While… Loop

Цикл Do While… Loop в VBA Excel предназначен для повторения блока операторов до тех пор, пока выполняется заданное условие (возвращается значение True). Этот цикл позволяет проверять условие как до, так и после выполнения операторов. Предусмотрен принудительный выход из цикла с помощью оператора Exit Do. Перейти к подробному описанию …

Цикл While… Wend

Цикл While… Wend в VBA Excel предназначен для выполнения блока операторов до тех пор, пока выполняется заданное условие (возвращается значение True). Этот цикл позволяет проверять условие только до выполнения операторов. Принудительный выход из цикла с помощью оператора Exit Do не предусмотрен. Перейти к подробному описанию …

Цикл Do Until… Loop

Цикл Do Until… Loop в VBA Excel предназначен для повторения блока операторов пока не выполняется заданное условие (возвращается значение False). Этот цикл позволяет проверять условие как до, так и после выполнения операторов. Предусмотрен принудительный выход из цикла с помощью оператора Exit Do. Перейти к подробному описанию …

Цикл For Each… Next

Цикл For Each… Next в VBA Excel предназначен для выполнения блока операторов по отношению к каждому элементу из группы элементов (диапазон, массив, коллекция). Предусмотрен принудительный выход из цикла с помощью оператора Exit For. Перейти к подробному описанию …

A loop is an essential concept for any programming language, and VBA follows the same approach. You can use loops to repeat an action until a specified condition is reached, or move through objects in a group, e.g. all worksheets in a workbook. A loop is an essential concept for programming. In this guide, we’re going to show you how to create a VBA loop in Excel.

Download Workbook

VBA loops can be useful to automate tasks. For example, you may need to protect or unprotect every worksheet at once, iterate a calculation for a specific number of times, or loop cells and store their values into an array until you find an empty cell. The rest is up to your needs and imagination.

VBA has two main loop categories:

  • For…Next Loops
  • Do Loops

In generally, while For…Next loops are designed for specific amount of iterations, Do loops are good for iterating based on a condition. However, you can modify and configure both loop types by their individual keywords. Let’s see the loop types with examples.

For…Next VBA Loop

For…Next (also known as For) loops are where you start to create VBA loops in Excel. A For loop is a basic concept of a loop structure in all programming languages. A For…Next loop is good for if you want to iterate you code certain amount of times, and for when you need to use the counter. For example, if you want to check cells from A1 to A10, a counter clicks from 1 to 10 can work in that case. Let’s see its syntax and an example.

Syntax

For counter = start To end [ Step step ]
statements ]
Exit For ]
statements ]
Next [ counter ]

Part Description
counter Required. Numeric variable used as a loop counter. The variable can’t be a Boolean or an array element.
start Required. Initial value of counter.
end Required. Final value of counter.
step Optional. Amount counter is changed each time through the loop. If not specified, step defaults to one.
statements Optional. One or more statements between For and Next that are executed a specific number of times.

Example 1 – Basic Form

In the first example of For…Next loop, we attempt to write serial numbers into the cells in A1:A10. In this code, For…Next loop sets values from 1 to 10 into the variable i. After the variable gets its value, you can use it in the code. We used the variable to specify the row numbers and cell values. Finally, the Next row increases the variable’s row by 1, and cycle goes on until the variable is equal to 11.

Sub FillSerialNumbers()
    Dim i As Integer
    For i = 1 To 10
        ActiveSheet.Cells(i, 1) = i
    Next i
End Sub

How to create VBA loops in Excel - For Next

Example 2 – Step

By default, For…Next loop increases its counter variable by 1 for each loop. You can change this property by using the step argument. To specify a step argument, use the Step keyword after the end argument and enter a number. Step can be either a positive or negative.

The following code is a modified version of the first example. Step 2 argument is added to loop. In this loop, the variable i can only take «1, 3, 5, 7, 9» values.

Sub FillSerialNumbers_Step2()
    Dim i As Integer
    For i = 1 To 10 Step 2
        ActiveSheet.Cells(i, 1) = i
    Next i
End Sub

Remember to choose appropriate start and end arguments when you need to use a negative step value. For example, For I = 10 To 1 Step -1

Example 3 – Nested Loops

You can create loops within other loops. VBA executes all iterations in an inner loop, for each iteration of the outer loop. This type of structure can be helpful if you want add additional dimensions into your code. For example, while one loop is counting rows, other can count the columns. You need three loops to fill a three-dimensional data array.

The important point is using different counter variables for each loop. Otherwise, there will be leaps for the counter values. Let’s see an example for nested For…Next loops.

The following code contains 2 For…Next loops which is using variables named i and j. In the statement panel, i and j are used as row and column numbers respectively.

In the first run, i becomes 1 and j becomes 2. After code is executed in the j-loop, while i keeps its value (1), j becomes 3. This cycle goes on until j becomes 7. After this, i becomes 2 and j returns back to 2.

Sub FillSerialNumbers_Nested()
    Dim i As Integer, j As Integer
    For i = 1 To 10
        For j = 2 To 6
            ActiveSheet.Cells(i, j) = i * j
        Next j
    Next i
End Sub

Since j gets numbers between 2 and 6, only columns from B to F are filled.

Example 4 – Exit For

You may want to exit a loop when a certain condition is met. Let’s say we do not want to fill cells if i * j is more than 18. To achieve this, we can use Exit For statement.

The following code uses Exit For in the inner loop. Please note that, Exit For works for only the loop it’s in. Thus, when i * j > 18 condition is met, VBA continues to run the outer loop (i-loop).

Sub FillSerialNumbers_ExitFor()
    Dim i As Integer, j As Integer
    For i = 1 To 10
        For j = 2 To 6
            If i * j > 18 Then Exit For
            ActiveSheet.Cells(i, j) = i * j
        Next j
    Next i
End Sub

Example 5 — For Each

A For Each loop is a more specialized version of the For…Next loops. For Each loops can iterate for elements in a list. These elements can be values in an array, cells in a range, or worksheets in workbook. For Each loops doesn’t need a counter, each element is stored in a variable to be used in the code.

Let’s take another example. This time there isn’t a counter variable, but a range object c. For Each loop assigns each cell in the range «A1:C8» to element c, at each iteration. Also, since there is no counter value, we need to increase an integer by 1 in the code.

Sub FillSerialNumbers_ForEach()
    Dim c As Range, i As Integer
    i = 0
    For Each c In ActiveSheet.Range("A1:C8")
        i = i + 1
        c = i
    Next c
End Sub

How to create VBA loops in Excel - For Each

This is the last example for the For…Next loops of our how to create a VBA loop in Excel guide. Let’s now move on to the Do loops.

Do VBA Loop

A Do loop looks at whether a condition is met to continue cycling through, or stop a loop. Do loops are more flexible than For…Next loops. On the other hand, this flexibility comes with some complexities.

A Do loop starts with Do and finishes with Loop keywords. You can define a condition for one of these statements. If you specify a condition with Do, VBA looks at the condition first; otherwise, the code block in the loop is executed and the condition is evaluated at the end. This flexibility presents 2 syntaxes.

Also, Do loops can use While and Until keywords to specify the action when a condition is met. If you use the While keyword, the loop continues to work if condition is met. On the other hand, the Until keyword stops the loop.

Syntax

Do [{ While | Until } condition ]
statements ]
Exit Do ]
statements ]
Loop

Or, you can use this syntax:

Do
statements ]
Exit Do ]
statements ]
Loop [{ While | Until } condition ]

Part Description
condition Optional. Numeric expression or string expression that is True or False. If condition is Null, condition is treated as False.
statements One or more statements that are repeated while, or until, condition is True.

Example 1 – Do While

Do While loop iterates its statements as long as the specified conditions are valid. We can modify our first example to work with a Do loop.

In the following example, the Do loop works as many iterations as the variable i is equal or less than 10.

Sub FillSerialNumbers_DoWhile()
    Dim i As Integer
    i = 1
    Do While i <= 10
        ActiveSheet.Cells(i, 1) = i
        i = i + 1
    Loop
End Sub

Caution: If you use a loop like this, remember to add a code to change the value of the variable. Otherwise, the code will be stuck in an infinite loop because the variable i will always remain less than 10.

How to create VBA loops in Excel - Do Loop

Example 2 — Do Until

This time the loop continues «until» the condition is met. Once it does, the loop ends.

Sub FillSerialNumbers_DoUntil()
    Dim i As Integer
    i = 1
    Do Until i > 10
        ActiveSheet.Cells(i, 1) = i
        i = i + 1
    Loop
End Sub

Example 3 – Loop While

You can use conditions after Loop as well. In this scenario, you ensure that the statements are executed at least once before condition validation.

Loop While iterates the loop if the supplied condition is met.

Sub FillSerialNumbers_DoLoopWhile()
    Dim i As Integer
    i = 1
    Do
        ActiveSheet.Cells(i, 1) = i
        i = i + 1
    Loop While i <= 10
End Sub

Example 4 – Loop Until

Use Loop Until statement when you need to check the condition after the statements, and want to continue the loop «until» the condition is met.

Sub FillSerialNumbers_DoLoopUntil()
    Dim i As Integer
    i = 1
    Do
        ActiveSheet.Cells(i, 1) = i
        i = i + 1
    Loop Until i > 10
End Sub

That’s all! You can now create your own VBA loop to automate your Excel tasks in no time.

На чтение 13 мин. Просмотров 26.5k.

VBA While Loop

Рамакришна, Источники индийской мудрости

Сейчас … мы идем по кругу

Эта статья содержит полное руководство по VBA Do While и VBA While Loops. (Если вы ищете информацию о циклах VBA For и For Each, перейдите сюда)

Цикл VBA While существует, чтобы сделать его совместимым со старым кодом. Однако Microsoft рекомендует использовать цикл Do Loop, поскольку он более «структурирован и гибок». Оба этих цикла рассматриваются в этом посте.

Для быстрого ознакомления с этими циклами перейдите к таблице быстрого руководства ниже.

Если вы ищете что-то конкретное, вы можете посмотреть содержание ниже.

Содержание

  1. Краткое руководство по VBA While Loops
  2. Введение
  3. Цикл For против цикла Do While
  4. Условия
  5. Формат цикла Do
  6. Цикл Exit Do
  7. While Wend
  8. Бесконечный цикл
  9. Использование функций Worksheet вместо циклов
  10. Резюме

Краткое руководство по VBA While Loops

Формат цикла Описание Пример
Do While … Loop Запускается 0 или более раз, пока условие выполняется Do While result = «Верно»
Loop
Do … Loop While Запускается 1 или более раз, пока условие выполняется Do 
Loop While result = «Верно»
Do Until … Loop Запускается 0 или более раз, пока условие не будет выполнено Do Until result <> «Верно»
Loop
Do … Until Loop Запускается 1 или более раз, пока условие не будет выполнено Do 
Loop Until result <> «Верно»
While … Wend
R
Запускается 0 или более раз, пока условие истинно.
Примечание: этот цикл считается устаревшим.
While result = «Верно»
Wend
Exit the Do Loop Завершает Do Do While i < 10
   i = GetTotal
   If i < 0 Then
      Exit Do
   End If
Loop

Введение

Если вы никогда ранее не использовали циклы, тогда вы можете прочитать «Что такое циклы и зачем они вам нужны» из моего поста в журнале For Loop.

Я собираюсь сосредоточиться в основном на Do Loop в этой статье. Как я упоминал выше, мы видели, что цикл While Wend считается устаревшим. Для полноты информации я все равно его включил в эту статью.

Итак, во-первых, зачем нам нужны циклы Do While, когда у нас уже есть циклы For?

Цикл For против цикла Do While

Когда мы используем цикл For Loop, мы заранее знаем, сколько раз мы хотим его запустить. Например, мы можем захотеть запустить цикл один раз для каждого элемента в коллекции, массиве или словаре.

В следующем примере кода мы видим в начале каждого цикла, сколько раз он будет выполняться.

' запускается 5 раз
For i = 1 To 5

' запускается один раз для каждого элемента коллекции
For i = 1 To coll.Count

' запускается один раз для каждого элемента в arr
For i = LBound(arr) To coll.lbound(arr)

' запускается один раз для каждого значения от 1 до значения в lastRow
For i = 1 To lastRow

' запускается один раз для каждого элемента в коллекции
For Each s In coll

Цикл Do другой. Он работает:

  • В то время как условие верно
  • Пока условие не будет выполнено

Другими словами, количество циклов в большинстве случаев не имеет значения.

Итак, что такое условие и как мы их используем?

Условия

Условие — это утверждение, которое оценивается как истинное или ложное. Они в основном используются с операторами Loops и If. При создании условия вы используете такие знаки, как >, <, <>,> =, =.

Ниже приведены примеры условий

Условие Истина, когда…
x < 5 x меньше 5
x <= 5 x меньше либо равен 5
x > 5 x больше 5
x >= 5 x больше либо равен 5
x = 5 x равен 5
x <> 5 x не равен 5
x > 5 And x < 10 x больше 5 И меньше 10
x = 2 Or x >10 x равен 2 ИЛИ больше 10
Range(«A1») = «Иван» Ячейка A1 содержит текст «Иван»
Range(«A1») <> «Иван» Ячейка A1 не содержит текст «Иван»

Вы могли заметить x = 5 как условие. Его следует путать с х = 5, при использовании в качестве назначения.

Например

' означает: значение 6 будет храниться в х
x = 6

' означает: х равен 6?
If x = 6

' означает: х равен 6?
Do While x = 6

В следующей таблице показано, как «=» используется в условиях и назначениях.

Использование «=» Тип Имеется в виду
Loop Until x = 5 Условие x равен 5?
Do While x = 5 Условие x равен 5?
If x = 5 Then Условие x равен 5?
For x = 1 To 5 Присваивание Установите значение x = 1, затем = 2 и т.д.
x = 5 Присваивание Установите значение x=5
b = 6 = 5 Присваивание и
условие
Присвойте b
результату условия
6 = 5
x = MyFunc(5,6) Присваивание Присвойте х
значение,
возвращаемое
функцией

Формат цикла Do

Цикл Do можно использовать четырьмя способами, и это часто вызывает путаницу. Однако в каждом из этих четырех способов есть только небольшая разница.

Do всегда в начале первой строки, а Loop всегда в конце последней строки.

Мы можем добавить условие после любой строки.

Do [условие]
Loop

Do 
Loop [условие]

Условию предшествует While или Until, которое дает нам эти четыре возможности

Do While [условие]
Loop

Do Until [условие]
Loop

Do 
Loop While [условие]

Do 
Loop Until [условие]

Давайте посмотрим на некоторые примеры, чтобы прояснить это.

Примеры цикла Do

Представьте, что вы хотите, чтобы пользователь ввел список элементов. Каждый раз, когда пользователь вводит элемент, вы печатаете его в «Immediate Window». Когда пользователь вводит пустую строку, вы хотите, чтобы приложение закрывалось.

В этом случае цикл For не подойдет, поскольку вы не знаете, сколько элементов будет вводить пользователь. Пользователь может ввести пустую строку первым или с сотой попытки. Для этого типа сценария вы бы использовали цикл Do.

Следующий код показывает это

 Dim sCommand As String

    Do
        ' Получить пользовательский ввод
        sCommand = InputBox("Пожалуйста, введите элемент")

        ' Печать в Immediate Window (Ctrl + G для просмотра)
        Debug.Print sCommand

    Loop While sCommand <> ""

Код входит в цикл и продолжается до тех пор, пока не достигнет строки «Loop While». На этом этапе он проверяет, оценивается ли условие как истинное или ложное.

Если условие оценивается как ложное, то код выходит из цикла и продолжается.
Если условие оценивается как истинное, то код возвращается к строке Do и снова проходит через цикл.
Разница между наличием условия на линии Do и на линии Loop очень проста.

Когда условие находится в строке Do, цикл может вообще не работать. Так что он будет работать ноль или более раз.
Когда условие находится на линии Loop, цикл всегда будет запущен хотя бы один раз. Так что он будет запущен один или несколько раз.

В нашем последнем примере условие находится в строке Loop, потому что мы всегда хотим получить хотя бы одно значение от пользователя. В следующем примере мы используем обе версии цикла. Цикл будет выполняться, пока пользователь не введет букву «н».

Sub GetInput()

    Dim sCommand As String

    ' Условие в начале
    Do While sCommand <> "н"
        sCommand = InputBox("Пожалуйста, введите элемент для цикла 1")
    Loop

    ' Условие в конце
    Do
        sCommand = InputBox("Пожалуйста, введите элемент для цикла 2")
    Loop While sCommand <> "н"

End Sub

В приведенном выше примере оба цикла будут вести себя одинаково.

Однако, если мы установим для sCommand значение «н» до запуска цикла «Do While», код не войдет в цикл.

Sub GetInput2()

    Dim sCommand As String
    sCommand = "н"

    ' Цикл не будет работать, поскольку команда "н"
    Do Whilel sCommand <> "н"
        sCommand = InputBox("Пожалуйста, введите элемент для цикла 1")
    Loop

    ' Цикл все равно будет запущен хотя бы один раз
    Do
        sCommand = InputBox("Пожалуйста, введите элемент для цикла 2")
    Loop While sCommand <> "н"

End Sub

Второй цикл в вышеприведенном примере (то есть Loop While) всегда будет запускаться хотя бы один раз.

While против Until

При использовании Do Loop условию должно предшествовать Until или While.

Until и While, по сути, противоположны друг другу. Они используются в VBA аналогично тому, как они используются в английском языке.

Например:

  • Оставьте одежду, пока не пойдет дождь
  • Оставь одежду, пока не идет дождь

Другой пример:

  • Оставайся в постели, пока не станет светло
  • Оставайся в постели, пока темно

Еще один пример:

  • повторять, пока число не станет больше или равно десяти
  • повторить пока счет меньше десяти

Как видите, использование Until и While — это просто противоположный способ написания одного и того же условия.

Примеры Until и While

Следующий код показывает циклы «While» и «Until» рядом. Как видите, единственная разница в том, что условие полностью изменено.

Примечание: знаки <> означают «не равно».

Sub GetInput()

    Dim sCommand As String

    ' Условие в начале
    Do Until sCommand = "н"
        sCommand = InputBox("Пожалуйста, введите элемент для цикла 1")
    Loop

    Do While sCommand <> "н"
        sCommand = InputBox("Пожалуйста, введите элемент для цикла 1")
    Loop

    ' Условие в конце
    Do
        sCommand = InputBox("Пожалуйста, введите элемент для цикла 2")
    Loop Until sCommand = "н"

    Do
        sCommand = InputBox("Пожалуйста, введите элемент для цикла 2")
    Loop While sCommand <> "н"

End Sub
  • Первый цикл: запускается только в том случае, если sCommand не равен ‘н’.
  • Второй цикл: запускается только в том случае, если sCommand не равен ‘н’.
  • Третий цикл: будет запущен хотя бы один раз перед проверкой sCommand.
  • Четвертый цикл: будет запущен хотя бы один раз перед проверкой sCommand.

Пример: проверка объектов

Примером использования Until и While является проверка объектов. Когда объект не был назначен, он имеет значение Nothing.

Поэтому, когда мы объявляем переменную книги в следующем примере, она имеет значение Nothing, пока мы не назначим ее Workbook.

Противоположностью Nothing не является Nothing, что может сбить с толку.

Представьте, что у нас есть две функции: GetFirstWorkbook и GetNextWorkbook, которые возвращают некоторые объекты книги. Код будет печатать имя рабочей книги до тех пор, пока функции больше не вернут действительную рабочую книгу.

Вы можете увидеть пример кода здесь:

Dim wrk As Workbook
    Set wrk = GetFirstWorkbook()

    Do Until wrk Is Nothing
        Debug.Print wrk.Name
        Set wrk = GetNextWorkbook()
    Loop

Написание этого кода с использованием Do While было бы более запутанным, так как условие Not Is Nothing

Dim wrk As Workbook
    Set wrk = GetFirstWorkbook()

    Do While Not wrk Is Nothing
        Debug.Print wrk.Name
        Set wrk = GetNextWorkbook()
    Loop

Это делает код более понятным, и наличие четких условий — всегда хорошо. Честно говоря, разница маленькая, и выбор между «While» и «Until» действительно сводится к личному выбору.

Цикл Exit Do

Мы можем выйти из любого цикла Do с помощью оператора Exit Do.

Следующий код показывает пример использования Exit Do

Do While i < 1000
     If Cells(i,1) = "Найдено" Then 
         Exit Do
     End If
     i = i + 1
Loop 

В этом случае мы выходим из цикла Do Loop, если ячейка содержит текст «Найдено».

While Wend

Этот цикл в VBA, чтобы сделать его совместимым со старым кодом. Microsoft рекомендует использовать циклы Do, поскольку они более структурированы.

Из MSDN: «Оператор Do… Loop обеспечивает более структурированный и гибкий способ выполнения циклов».

Формат цикла VBA While Wend

Цикл VBA While имеет следующий формат:

While <Условие>
Wend

While Wend против Do

Разница между циклами VBA While и VBA Do заключается в следующем:

  1. While может иметь условие только в начале цикла.
  2. While не имеет версии Until.
  3. Не существует оператора для выхода из цикла While, как Exit For или Exit Do.

Условие для цикла VBA While такое же, как и для цикла VBA Do While. Два цикла в приведенном ниже коде работают точно так же.

Sub GetInput()

    Dim sCommand As String

    Do While sCommand <> "н"
        sCommand = InputBox("Пожалуйста, введите элемент для цикла 1")
    Loop

    While sCommand <> "н"
        sCommand = InputBox("Пожалуйста, введите элемент для цикла 2")
    Wend

End Sub

Бесконечный цикл

Даже если вы никогда не писали код в своей жизни, я уверен, что вы слышали фразу «Бесконечный цикл». Это цикл, в котором условие никогда не будет выполнено. Обычно это происходит, когда вы забыли обновить счетчик.

Следующий код показывает бесконечный цикл

Dim cnt As Long
    cnt = 1

    'это бесконечный цикл
    Do While cnt <> 5

    Loop

В этом примере cnt установлен в 1, но он никогда не обновляется. Поэтому условие никогда не будет выполнено — cnt всегда будет меньше 5.

В следующем коде cnt обновляется каждый раз, поэтому условие будет выполнено.

Dim cnt As Long
    cnt = 1

    Do While cnt <> 5
        cnt = cnt + 1
    Loop

Как вы можете видеть, использование For Loop безопаснее для подсчета, поскольку оно автоматически обновляет счет в цикле. Ниже приведен тот же цикл с использованием For.

Dim i As Long
    For i = 1 To 4

    Next i

Это явно лучший способ сделать это. Цикл For устанавливает начальное значение, условие и счет в одну строку.

Конечно, можно использовать бесконечный цикл, используя For — это потребует немного больше усилий 🙂

 Dim i As Long
    ' Бесконечный цикл
    For i = 1 To 4
        ' i никогда не достигнет 4
        i = 1
    Next i

Работа с бесконечным циклом

Когда у вас бесконечный цикл — VBA не выдаст ошибку. Ваш код будет продолжать работать, а редактор Visual Basic не будет отвечать.

Раньше вы могли выйти из цикла, просто нажав Ctrl и Break. В настоящее время разные ноутбуки используют разные комбинации клавиш. Полезно знать, как это настроено в вашем ноутбуке, чтобы в случае возникновения бесконечного цикла вы могли легко остановить код.

Вы также можете выйти из цикла, убив процесс. Нажмите Ctrl + Shift + Esc. На вкладке Процессы найдите Excel / Microsoft Excel. Щелкните правой кнопкой мыши по этому и выберите «Завершить процесс». Это закроет Excel, и вы можете потерять часть работы — так что гораздо лучше использовать Ctrl + Break или его эквивалент.

Использование функций Worksheet вместо циклов

Иногда вы можете использовать функцию листа вместо цикла.

Например, представьте, что вы хотите добавить значения в список ячеек. Вы можете сделать это с помощью цикла, но было бы более эффективно использовать функцию таблицы Sum. Это быстрее и экономит много кода.

Использовать функции рабочего листа очень просто. Ниже приведен пример использования Sum и Count.

Sub WorksheetFunctions()

    Debug.Print WorksheetFunction.Sum(Range("A1:A10"))

    Debug.Print WorksheetFunction.Count(Range("A1:A10"))

End Sub

В следующем примере используется цикл для выполнения того же действия. Как видите, это гораздо более длинный способ достижения той же цели.

Sub SumWithLoop()

    Dim total As Long, count As Long
    Dim rg As Range
    For Each rg In Range("A1:A10")
        ' Total
        total = total + rg
        ' Count
        If rg <> "" Then
            count = count + 1
        End If
    Next rg

    Debug.Print total
    Debug.Print count

End Sub

Резюме

Цикл Do While

  • Цикл Do можно использовать 4 способами.
  • Его можно использовать в начале или в конце, Do While .. Loop, Do … Loop While
  • Может использоваться с Until в начале или в конце, Do Until .. Loop, Do … Loop Until
  • While и Until используют противоположные условия друг к другу.
  • Бесконечный цикл происходит, если ваше условие выхода никогда не будет выполнено.
  • Иногда использование функции рабочего листа более эффективно, чем использование цикла.

Цикл While Wend

  • Цикл Wend Wend устарел, и вы можете вместо этого использовать цикл Do.

Понравилась статья? Поделить с друзьями:
  • Принтер для microsoft word
  • Принтер в формате excel
  • Принтер word печатает а pdf нет
  • Принадлежность ячейки диапазону в excel
  • Принадлежит отрезку в excel