Excel vba for each next for

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

Цикл For Each… Next в VBA Excel, его синтаксис и описание отдельных компонентов. Примеры использования цикла For Each… Next.

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

For Each element In group

    [ statements ]

    [ Exit For ]

    [ statements ]

Next [ element ]

В квадратных скобках указаны необязательные атрибуты цикла For Each… Next.

Компоненты цикла For Each… Next

Компонент Описание
element Обязательный атрибут в операторе For Each, необязательный атрибут в операторе Next. Представляет из себя переменную, используемую для циклического прохода элементов группы (диапазон, массив, коллекция), которая предварительно должна быть объявлена с соответствующим типом данных*.
group Обязательный атрибут. Группа элементов (диапазон, массив, коллекция), по каждому элементу которой последовательно проходит цикл For Each… Next.
statements Необязательный** атрибут. Операторы вашего кода.
Exit For Необязательный атрибут. Оператор выхода из цикла до его окончания.

*Если цикл For Each… Next используется в VBA Excel для прохождения элементов коллекции (объект Collection) или массива, тогда переменная element должна быть объявлена с типом данных Variant, иначе цикл работать не будет.

**Если не использовать в цикле свой код, смысл применения цикла теряется.

Примеры циклов For Each… Next

Цикл для диапазона ячеек

На активном листе рабочей книги Excel выделите диапазон ячеек и запустите на выполнение следующую процедуру:

Sub test1()

Dim element As Range, a As String

  a = «Данные, полученные с помощью цикла For Each… Next:»

    For Each element In Selection

      a = a & vbNewLine & «Ячейка « & element.Address & _

      » содержит значение: « & CStr(element.Value)

    Next

  MsgBox a

End Sub

Информационное окно MsgBox выведет адреса выделенных ячеек и их содержимое, если оно есть. Если будет выбрано много ячеек, то полностью информация по всем ячейкам выведена не будет, так как максимальная длина параметра Prompt функции MsgBox составляет примерно 1024 знака.

Цикл для коллекции листов

Скопируйте следующую процедуру VBA в стандартный модуль книги Excel:

Sub test2()

Dim element As Worksheet, a As String

  a = «Список листов, содержащихся в этой книге:»

    For Each element In Worksheets

      a = a & vbNewLine & element.Index _

      & «) « & element.Name

    Next

  MsgBox a

End Sub

Информационное окно MsgBox выведет список наименований всех листов рабочей книги Excel по порядковому номеру их ярлычков, соответствующих их индексам.

Цикл для массива

Присвоим массиву список наименований животных и в цикле For Each… Next запишем их в переменную a. Информационное окно MsgBox выведет список наименований животных из переменной a.

Sub test3()

Dim element As Variant, a As String, group As Variant

group = Array(«бегемот», «слон», «кенгуру», «тигр», «мышь»)

‘или можно присвоить массиву значения диапазона ячеек

‘рабочего листа, например, выбранного: group = Selection

a = «Массив содержит следующие значения:» & vbNewLine

  For Each element In group

    a = a & vbNewLine & element

  Next

MsgBox a

End Sub

Повторим ту же процедуру VBA, но всем элементам массива в цикле For Each… Next присвоим значение «Попугай». Информационное окно MsgBox выведет список наименований животных, состоящий только из попугаев, что доказывает возможность редактирования значений элементов массива в цикле For Each… Next.

Sub test4()

Dim element As Variant, a As String, group As Variant

group = Array(«бегемот», «слон», «кенгуру», «тигр», «мышь»)

‘или можно присвоить массиву значения диапазона ячеек

‘рабочего листа, например, выделенного: group = Selection

a = «Массив содержит следующие значения:» & vbNewLine

  For Each element In group

    element = «Попугай»

    a = a & vbNewLine & element

  Next

MsgBox a

End Sub

Этот код, как и все остальные в этой статье, тестировался в Excel 2016.

Цикл для коллекции подкаталогов и выход из цикла

В этом примере мы будем добавлять в переменную a названия подкаталогов на диске C вашего компьютера. Когда цикл дойдет до папки Program Files, он добавит в переменную a ее название и сообщение: «Хватит, дальше читать не буду! С уважением, Ваш цикл For Each… Next.».

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

Sub test5()

Dim FSO As Object, myFolders As Object, myFolder As Object, a As String

‘Создаем новый FileSystemObject и присваиваем его переменной «FSO»

Set FSO = CreateObject(«Scripting.FileSystemObject»)

‘Извлекаем список подкаталогов на диске «C» и присваиваем

‘его переменной «myFolders»

Set myFolders = FSO.GetFolder(«C:»)

a = «Папки на диске C:» & vbNewLine

‘Проходим циклом по списку подкаталогов и добавляем в переменную «a«

‘их имена, дойдя до папки «Program Files«, выходим из цикла

  For Each myFolder In myFolders.SubFolders

    a = a & vbNewLine & myFolder.Name

    If myFolder.Name = «Program Files» Then

      a = a & vbNewLine & vbNewLine & «Хватит, дальше читать не буду!» _

      & vbNewLine & vbNewLine & «С уважением,» & vbNewLine & _

      «Ваш цикл For Each... Next.«

  Exit For

    End If

  Next

Set FSO = Nothing

MsgBox a

End Sub

Информационное окно MsgBox выведет список наименований подкаталогов на диске C вашего компьютера до папки Program Files включительно и сообщение цикла о прекращении своей работы.

В результате работы программы будут выведены не только наименования подкаталогов, видимых при переходе в проводнике к диску C, но и скрытые и служебные папки. Для просмотра списка всех подкаталогов на диске C, закомментируйте участок кода от If до End If включительно и запустите выполнение процедуры в редакторе VBA Excel.


На чтение 14 мин. Просмотров 18.5k.

Итог: циклы For Next — одни из самых мощных методов VBA для автоматизации общих задач в Excel. В этой статье объясняется, как работает цикл, повторяющий действия над коллекцией элементов, что экономит нам массу времени.

Уровень мастерства: Средний

For Next Code Loop Explained for VBA Excel

Содержание

  1. Сила циклов VBA
  2. Как работает цикл For Next?
  3. Два типа циклов For Next
  4. The For Each Next Loop: цикл по коллекции элементов
  5. В каком порядке работает цикл For Each?
  6. Предметы / объекты НЕ выбираются в цикле
  7. The Next Loop: циклы через набор чисел
  8. Обратный цикл
  9. Как остановить цикл раньше
  10. Переменная не требуется после ключевого слова Next
  11. Примеры макросов VBA для циклов
  12. Какую задачу хотите зациклить вы?

Сила циклов VBA

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

Можете ли вы вспомнить несколько задач, в которых вам
приходилось повторять один и тот же процесс снова и снова?

Эти задачи чрезвычайно трудоемкие и скучные!

Repetitive Excel Tasks Get Boring - VBA Loop

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

Цикл For Next — это наиболее распространенный тип цикла,
который помогает нам выполнять эти повторяющиеся задания. В этой статье мы
рассмотрим два типа For Next Loops.

Загрузите файл примера

Загрузите бесплатный файл Excel, содержащий примеры макросов
с помощью цикла For Next.

For Next Loop VBA Macro Examples.xlsm (79.0 KB)

Скачать PDF версию статьи на английском для печати.

Как работает цикл For Next?

Цикл For Next позволяет нам просматривать коллекцию, элементами которой могут быть объекты или списки чисел.

Примеры коллекций:

  • Клетки в ассортименте.
  • Рабочие листы в рабочей тетради.
  • Открытые рабочие тетради на компьютере.
  • Сводные таблицы на листе.
  • Сводные поля в сводной таблице.
  • Формы на листе.
  • И любой другой объект, с которым вы взаимодействуете в Excel.

Задача цикла For Next Loop состоит в том, чтобы выполнять
одинаковые действия (строки кода) для каждого элемента в коллекции.

How a For Next Loop Works in VBA

В приведенном ниже примере содержится цикл For Next, который
проходит по каждому листу в книге и отображает каждый лист. Цикл начинается с
первого элемента в коллекции (первый лист в рабочей книге) и выполняет строку
кода между строками For и Next для каждого элемента в коллекции (каждый лист в
рабочей книге).

Sub Unhide_Multiple_Sheets()

Dim ws As Worksheet
    
    For Each ws In ActiveWorkbook.Worksheets
        ws.Visible = xlSheetVisible
    Next ws

End Sub

Конечно, мы можем использовать логические операторы, такие как операторы If, для проверки свойств и условий перед выполнением действий.

Следующий макрос отображает только те листы, которые имеют фразу «ABC Global Co.» в ячейке A1 каждого листа, и скрывает все остальные листы.

Sub Unhide_Report_Sheets()

Dim ws As Worksheet
    
    For Each ws In ActiveWorkbook.Worksheets
        If ws.Range("A1").Value = "ABC Global Co." Then
            ws.Visible = xlSheetVisible
        Else
            ws.Visible = xlSheetHidden
        End If
    Next ws

End Sub

Два типа циклов For Next

Действительно, существуют два типа For Next Loops.

  1. For Each Next
    Loops циклически просматривает коллекцию элементов.
  2. For Next Loops
    цикл через набор чисел.

Давайте посмотрим, как работает
каждый.

The For Each Next Loop: цикл по коллекции элементов

Как мы видели выше, цикл «The For Each Next Loop» позволяет нам перебирать коллекцию предметов или объектов. Это, наверное, самый распространенный цикл, который мы используем в Excel, потому что мы работаем с коллекциями объектов. Опять же, эти коллекции представляют собой ячейки в диапазоне, рабочие таблицы в рабочей книге, сводные таблицы в рабочей таблице и т.д.

For Each Next Loop Loops Through All Items Worksheets in a Collection

Мы будем использовать пример написания цикла «For Each Next Loop», чтобы просмотреть все рабочие листы в рабочей книге.

The For Each Next Loop Explained for Excel VBA

Существует четыре основных шага для написания цикла For Each Next в VBA:

  1. Объявите переменную для объекта.
  2. Напишите для каждой строки переменную и коллекцию
    ссылок.
  3. Добавьте строку (и) кода для повтора для каждого
    элемента в коллекции.
  4. Напишите следующую строку, чтобы закрыть цикл.

Давайте рассмотрим каждый из этих шагов подробно.

Шаг 1 — объявить переменную для объекта

Сначала нам нужно объявить переменную, которая будет
временно хранить ссылку на объект.

Строка Dim в верхней части макроса объявляет переменную, как объект. В этом случае объект является рабочим листом. Мы можем создать любое имя переменной, если захотим, если оно не совпадает с другой ссылкой в VBA. «Ws» — наиболее распространенное имя переменной для объекта листа, но вы можете изменить его.

Шаг 2 — Для каждой строки

Далее мы напишем оператор For Each. Это первая строка кода в цикле.

For Each ws In ActiveWorkbook.Worksheets

Первые два слова For Each. Затем мы вводим имя переменной, за которым следует слово In. Наконец, мы указываем, где располагается коллекция. В этом случае мы хотим просмотреть все рабочие листы в ActiveWorkbook. Итак, мы набираем ActiveWorkbook.Worksheets. Эта строка ссылается на все рабочие листы в ActiveWorkbook.

Если вы хотите пройтись по рабочим листам определенной
рабочей книги, вы можете использовать свойство Рабочие книги для ссылки на эту
рабочую книгу по имени.

For Each ws In Workbooks("Book2.xlsx").Worksheets

Просто помните, что рабочая книга, на которую вы ссылаетесь,
должна быть открыта до запуска строки кода For Next. Конечно, мы можем
использовать метод Workbooks.Open, чтобы открыть рабочую книгу.

Шаг 3 — Добавить код для повторения для каждой итерации

После строки «For Each» мы добавляем строку(и) кода, которая будет выполняться на каждом листе. В этом примере у нас есть только одна строка кода, которая показывает лист.

ws.Visible = xlSheetVisible

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

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

Однако нам НЕ нужна эта строка с циклом For Each Next. Цикл
заботится о настройке переменной для нас для каждой итерации в цикле.

Для первой итерации в цикле ws установлен на Worksheets (1).
На следующей итерации ws устанавливается в Worksheets (2). Это продолжается,
пока цикл перебирает все листы в рабочей книге. Это очень мощно, потому что мы
можем повторно использовать переменную для ссылки на лист в цикле несколько
раз.

Шаг 4 — Next закрывает цикл

Последняя строка кода в цикле — Next.

Когда макрос попадает в эту строку кода, он делает две вещи:

  1. Во-первых, он изменяет ссылку на переменную на следующий элемент коллекции. В этом примере переменная ws изменяется для ссылки на следующий лист в рабочей книге.
  2. Во-вторых, он возвращается к выполнению строки кода непосредственно под строкой For Each. Затем он выполняет все строки кода между строками For Each и Next в порядке сверху вниз.

What Happens When the Next Line Runs in a Loop Excel VBA

Когда будет достигнут последний элемент в коллекции (рабочий лист в рабочей книге), цикл останавливается, и макрос переходит к следующей строке кода ниже строки Next.

В каком порядке работает цикл For Each?

Цикл For Each Loop всегда начинается с первого элемента в коллекции и переходит к последнему элементу в том порядке, в котором они отображаются в Excel. Это основано на номере индекса предметов в коллекции. Вот несколько примеров порядка выполнения цикла для общих объектов.

  • Рабочие листы. Начинается с первой вкладки листа в рабочей книге и возвращается к последней в том порядке, в котором вкладки отображаются в рабочей книге.
  • Рабочие книги. Начинается с первой открытой книги и циклически повторяется в порядке открытия рабочих книг. Рабочим книгам присваивается порядковый номер по мере их открытия.
  • Клетки: циклы слева направо, затем вниз. Начинается с первой ячейки в диапазоне и возвращается к следующему столбцу в той же строке, затем переходит к следующей строке.
  • Таблицы и сводные таблицы. Начинается с первого объекта, созданного на листе, и циклически повторяется в порядке создания объектов. Этот же принцип действует и для других объектов, которые вы создаете на листах, таких как фигуры, диаграммы, слайсеры и т.д.

Предметы / объекты НЕ выбираются в цикле

Важно отметить, что когда мы перебираем коллекцию объектов, каждый объект НЕ выделяется в Excel.

VBA For Each примеры

Цикл создает ссылку на элемент/объект с помощью переменной. Переменная временно установлена на ссылку на объект. Объект НЕ выбран и НЕ обязательно становится активным объектом. Для выбора объекта мы можем использовать методы Select или Activate. Вы также должны убедиться, что объекты родительского объекта выбраны первыми. Ознакомьтесь с моей статьей об объектной модели Excel и иерархии объектов в VBA, чтобы узнать больше об этом.

The Next Loop: циклы через набор чисел

Также можно использовать цикл For Next Loop для просмотра набора чисел. Это может быть полезно, когда мы перебираем элементы управления пользовательской формы, массивы или если мы хотим перебрать коллекцию в обратном направлении.

VBA For Each примеры

Основная операция цикла For Next такая же, как и для цикла
For Each. Разница заключается в формате строки For.

Шаг 1 — Объявление переменной для числа

Чтобы перебрать набор чисел, мы сначала должны объявить переменную для целого числа типа данных. Мы можем использовать Integer или Long integer.

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

Дополнительное примечание к Long: тип данных Long (целое число) содержит большее число, чем Integer. Это занимает больше памяти, но для современного компьютера это не проблема. Мы можем использовать длинные переменные все время. Буква L выглядит как цифра 1 в VBA, поэтому я теперь использую i в качестве имени переменной, хотя я использую Long в качестве типа данных. Это все зависит от личных предпочтений, и вы можете назвать переменную как хотите.

Шаг 2 — Напишите строку For

Далее мы пишем строку For. Базовая конструкция — это ключевое слово For, за которым следует имя переменной (counter), затем знак равенства, начальное значение To end value.

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

For i = 1 To ActiveWorkbook.Worksheets.Count

Эта строка кода возвращает количество листов в активной книге. Тем не менее, он не проходит по каждому листу. Цикл просто перебирает набор чисел. Мы должны создать ссылку на лист с переменной счетчика (i) в качестве номера индекса свойства Worksheets. Шаг 3 показывает эту ссылку.

Шаг 3 — Добавить код, который повторяется для каждой итерации

Остальная часть цикла работает так же, как цикл For Each. Мы можем добавить строки между строками For и Next, которые будут выполняться для каждой итерации цикла. Переменная counter может быть использована несколько раз в этих строках кода.

Worksheets(i).Visible = True

Шаг 4 — Строка Next закрывает цикл

Наконец, мы добавляем строку Next внизу.

Когда макрос запускается, он устанавливает переменную, равную первому числу в строке For. Когда макрос попадает в следующую строку, он добавляет 1 к значению переменной или увеличивает счет. Итак, я = 2 во второй итерации цикла. Он продолжает цикл, пока не будет достигнут последний номер в цикле.

По умолчанию 1 добавляется к счетчику переменных для каждой итерации в цикле. Это называется значением шага, и мы можем контролировать значение каждого шага в счетчике. Значение Step добавляется в конец строки For. Следующая строка добавит 2 к счетчику для каждой итерации в цикле.

Если вы хотите заштриховать все остальные строки на листе, вы можете использовать такой цикл.

Обратный цикл

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

Обратите внимание, что начальное значение теперь больше, а конечное значение меньше. Циклы начинаются с 100 (начальное значение) и вычитают 1 из переменной счетчика (шаг -1) для каждой итерации в цикле, пока не дойдут до 1 (конечное значение).

Ключевое слово Step не является обязательным. Если вы не укажете его, тогда VBA примет значение шага 1.

Цикл в обратном направлении — это хорошо, если вы удаляете элементы.

Я напишу отдельный пост об этом, но общая идея заключается в том, что когда мы перебираем коллекцию и удаляем элементы, размер коллекции уменьшается при удалении элементов. Цикл обычно выдает ошибку, как только достигает 10-го элемента, когда в коллекции теперь только 9 элементов. Цикл в обратном направлении предотвращает эту потенциальную ошибку.

Как остановить цикл раньше

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

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

Sub Unhide_First_Sheet_Exit_For()
' Отображает первый лист, который содержит определенную фразу
' в имени листа, затем выходит из цикла.

Dim ws As Worksheet
    
    For Each ws In ActiveWorkbook.Worksheets
    
        ' Найдите лист, который начинается со слова «Отчет»
        If Left(ws.Name, 6) = "Report" Then
            
            ws.Visible = xlSheetVisible
            
            ' Выход из цикла после того, как первый лист найден
            Exit For
        
        End If
    Next ws

End Sub

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

VBA For Each примеры

Переменная не требуется после ключевого слова Next

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

Это НЕ обязательно, и вы можете не увидеть его в других примерах, которые вы найдете в Интернете. Однако мне нравится включать переменную после Next по двум причинам.

  1. Мы можем использовать его при отладке кода,
    чтобы увидеть значение переменной, наведя указатель мыши на переменную, когда
    код остановлен.
  2. Это облегчает понимание того, к какой строке For
    подключена следующая строка. Это особенно верно, когда у вас есть несколько циклов
    или вложенных циклов в ваших макросах.

VBA For Each примеры

Поэтому я рекомендую добавить переменную после ключевого слова Next в качестве лучшей практики. Немного дополнительной работы заранее сэкономит время и головную боль в будущем. Доверьтесь мне!

Примеры макросов VBA для циклов

Вот дополнительные статьи с макросами, в которых используется хотя бы один цикл For Next Loop.

3 способа показать несколько листов в учебнике по Excel + VBA

Автоматическое форматирование чисел по умолчанию в сводных таблицах Excel

3 совета, как сохранить и закрыть все открытые файлы книги Excel + макрос

Макрос метрики SUBTOTAL — создание сводной таблицы всех
типов функций

Как добавить оглавление Галерея изображений в файлы Excel

Скрыть и отобразить (отфильтровать) столбцы с помощью
слайсера или раскрывающегося меню фильтра

Фильтрация сводной таблицы или среза по самой последней дате или периоду

Как изменить размер панелей Excel для разных размеров экрана

Преобразование сводной таблицы в формулы SUMIFS + бесплатный макрос VBA

Макрос VBA, чтобы скрыть все столбцы, которые содержат
значение в ячейке

Как повторять задачи с помощью кода VBA — Looping — Отличная статья с большим количеством примеров от моего друга Криса Ньюмана из The Spreadsheet Guru.

Какую задачу хотите зациклить вы?

Я надеюсь, что эта статья поможет вам начать работу с циклами. Не забудьте скачать бесплатный файл Excel, содержащий примеры кода.

For Next Loop VBA Macro Examples.xlsm (79.0 KB)

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

Пожалуйста, оставьте комментарий ниже с задачей, которую вы хотите автоматизировать с помощью цикла. Спасибо!

Bottom line: The For Next Loops are some of the most powerful VBA macro coding techniques for automating common tasks in Excel.  This article explains how the loop works to repeat actions on a collection of items, which saves us a ton of time with our jobs.

Skill level: Intermediate

For Next Code Loop Explained for VBA Excel

The Power of VBA Loops

In Excel we spend a lot of time repeating simple tasks.  This could be actions like: formatting multiple ranges, unhiding multiple sheets, copying and pasting to several workbooks, apply filters to multiple tables or pivot tables, replacing values, updating formulas, etc.

Can you think of a few tasks where you had to repeat the same process over and over again?

These tasks can be extremely time consuming and BORING!

Repetitive Excel Tasks Get Boring - VBA Loop

Fortunately, there is a way out.  We can use loops in our VBA macros to repeat actions very quickly.  Tasks that can take hours to do manually can be completed in a matter of seconds with a loop.

The For Next Loop is the most common type of loop that helps us with these repetitive jobs.  In this article we will look at the two types of For Next Loops.

Download the Example File

Download the free Excel file that contains examples of macros with the For Next Loop.

Download a PDF version of the article for printing.

How Does the For Next Loop Work?

The For Next Loop allows us to loop through a collection of items in Excel.  The collection can be a collection of objects or a list of numbers.

Examples of collections of objects include:

  • Cells in a range.
  • Worksheets in a workbook.
  • Open workbooks on the computer.
  • Pivot tables in a worksheet.
  • Pivot fields in a pivot table.
  • Shapes on a worksheet.
  • And any other object you interact with in Excel.

The job of the For Next Loop is to perform the same actions (lines of code) on each item in the collection.

How a For Next Loop Works in VBA

The example below contains a For Next Loop that loops through each worksheet in the workbook and unhides each sheet.  The loop starts at the first item in the collection (the first sheet in the workbook), and performs the line(s) of code between the For and Next lines for each item in the collection (every sheet in the workbook).

Sub Unhide_Multiple_Sheets()

Dim ws As Worksheet
    
    For Each ws In ActiveWorkbook.Worksheets
        ws.Visible = xlSheetVisible
    Next ws

End Sub

Of course we can use logical statements like If statements to test properties and conditions before performing the actions.  The following macro only unhides sheets that have the phrase “ABC Global Co.” in cell A1 of each sheet, and hides all other sheets.

Sub Unhide_Report_Sheets()

Dim ws As Worksheet
    
    For Each ws In ActiveWorkbook.Worksheets
        If ws.Range("A1").Value = "ABC Global Co." Then
            ws.Visible = xlSheetVisible
        Else
            ws.Visible = xlSheetHidden
        End If
    Next ws

End Sub

The Two Types of For Next Loops

There are really two types of For Next Loops.

  1. For Each Next Loops loop through a collection of items.
  2. For Next Loops loop through a set of numbers.

Let’s take a look at how each works.

The For Each Next Loop: Loops Through a Collection of Items

As we saw above, the The For Each Next Loop allows us to loop through a collection of items or objects.  This is probably the most common loop we use in Excel because we are working with collections of objects.  Again, these collections are the cells in a range, worksheets in a workbook, pivot tables in a worksheet, etc.

For Each Next Loop Loops Through All Items Worksheets in a Collection

We will use the example of writing a For Each Next Loop to loop through all the worksheets in a workbook.

The For Each Next Loop Explained for Excel VBA

There are 4 basic steps to writing a For Each Next Loop in VBA:

  1. Declare a variable for an object.
  2. Write the For Each Line with the variable and collection references.
  3. Add line(s) of code to repeat for each item in the collection.
  4. Write the Next line to close the loop.

Let’s take a look at each of these steps in detail.

Step 1 – Declare a Variable for an Object

We first need to declare a variable that will temporarily store a reference to the object.

The Dim line at the top of the macro declares a variable as an object.  In this case the object is a worksheet.  We can create any variable name we want as long as it is not the same as another reference in VBA.  “ws” is the most common variable name for a worksheet object, but you can change this.

Dim ws As Worksheet

Step 2 – The For Each Line

Next we will write the For Each statement.  This is the first line of code in the loop.

For Each ws In ActiveWorkbook.Worksheets

The first two words are For Each.  Then we type the variable name, followed by the word In  Finally, we specify where the collection exists.  In this case we want to loop through all the worksheets in the ActiveWorkbook.  So, we type ActiveWorkbook.Worksheets.  That line references all the worksheets in the ActiveWorkbook.

If you want to loop through worksheets of a specific workbook, then you can use the Workbooks property to reference that workbook by name.

For Each ws In Workbooks("Book2.xlsx").Worksheets

Just remember that the workbook you reference has to be open before the For Next line of code runs.  Of course, we can use the Workbooks.Open method to open the workbook as well.

Step 3 – Add Code to Repeat for Each Iteration

After the For Each line, we add the line(s) of code that will be performed on each sheet.  In this example we just have one line of code that unhides the sheet.

ws.Visible = xlSheetVisible

In this line of code we are using the ws variable to reference the current worksheet in the loop.  When the loop runs, it sets a temporary reference to the ws variable for each iteration in the loop.

This would be the same as if we were to set the ws variable to a specific sheet using the following line of code.

Set ws = Worksheets(1)

However, we do NOT need this line with the For Each Next Loop.  The loop takes care of setting the variable for us for each iteration in the loop.

For the first iteration in the loop, the ws is set to Worksheets(1).  In the next iteration, ws is set to Worksheets(2).  This continues as the loop iterates through all sheets in the workbook.  This is very powerful because we can reuse the variable to reference the worksheet several times within the the loop.

Step 4 – The Next Line Loops Back

The final line of code in the loop is the Next line.

Next ws

When the macro hits this line of code it does two things:

  1. First, it changes the variable reference to the next item in the collection.  In this example, the ws variable is changed to reference the next sheet in the workbook.
  2. Second, it loops back up to the run the line of code directly below the For Each line.  It then runs all the lines of code between the For Each and Next lines in top to bottom order.

What Happens When the Next Line Runs in a Loop Excel VBA

When the last item in the collection (worksheet in the workbook) is reached, the looping stops, and the macro continues on to the next line of code below the Next line.

What Order Does the For Each Loop Run In?

The For Each Loop always starts at the first item in the collection and loops through to the last item in the order they appear in Excel.  This is based on the index number of the items in the collection.  Here are some examples of the order the loop runs in for common objects.

  • Worksheets: Starts at the first sheet tab in the workbook and loops to the last in the order the tabs are displayed in the workbook.
  • Workbooks: Starts at the first workbook that was opened and loops in the order that workbooks were opened.  Workbooks are assigned an index number as they are opened.
  • Cells: Loops left-to-right, then down.  Starts in the first cell in the range and loops to the next column in the same row, then goes to the next row.
  • Tables & Pivot Tables: Starts with the first object that was create in the sheet and loops in the order the objects were created.  This same principle is true for other objects you create in sheets like shapes, charts, slicers, etc.

Items/Objects Are NOT Selected in the Loop

It’s important to note that when we loop through a collection of objects, each object is NOT selected in Excel.

Loops Do NOT Select Each Item or Object

The loop creates a reference to the item/object with the variable.  The variable is temporarily set to a reference of the object.  The object is NOT selected and does NOT necessarily become the active object.  To select the object we can use the Select or Activate methods.  You would also have to make sure the objects parent object(s) are selected first.  Checkout my article on the Excel Object Model and Object Hierarchy in VBA for more on this.

The Next Loop: Loops Through a Set of Numbers

We can also use the For Next Loop to loop through a set of numbers.  This can be useful when we are looping through userform controls, arrays, or if we want to loop through a collection backwards.
For Next Loop Code Explained Excel VBA Macro
The basic operation of the For Next Loop is the same as the For Each Loop.  The difference is the format of the For line.

Step 1 – Declare a Variable for a Number

To loop through a set of numbers we first need to declare a variable to a whole number data type.  We can use Integer or Long integer.

Dim i As Long

The variable is referred to as the Counter because it increments or counts up/down for each iteration in the loop.

A side note on Long: The Long (integer) data type holds a bigger number than Integer.  It takes up more memory, but today’s computer have so much memory that it’s no longer a problem.  We can use Long variables all the time.  The letter L looks like the number 1 in VBA, so I’m now using i as the variable name even though I use Long as the data type.  This is all a matter of personal preference and you can name the variable whatever you want.

Step 2 – Write the For Statement

Next we write the For statement.  The basic construct is the keyword For, followed by the variable name (counter), then equals sign, start value To end value.

For i = 1 To 10

The start and end values can be referenced as numbers, or we can use integer/long variables in their place.

For i = iStart To iEnd

We can also use properties of objects that return a number.

For i = 1 To ActiveWorkbook.Worksheets.Count

That line of code would return the number of sheets in the active workbook.  However, it is NOT looping through each worksheet.  The loop is just looping through a set of numbers.  We have to create a reference to a worksheet with the counter variable (i) as the index number of the Worksheets property.  Step 3 shows this reference.

Step 3 – Add Code that Repeats for Each Iteration

The rest of the loop functions the same as the For Each loop.  We can add lines between the For and Next lines that will run for each iteration of the loop.  The counter variable can be used multiple times in these lines of code.

Worksheets(i).Visible = True

Step 4 – The Next Line Increments the Number & Loops Back

Finally, we add the Next line at the bottom.

Next i

When the macro runs it will set the variable equal to the first number in the For line.  When the macro hits the Next line, it will add 1 to the value of the variable, or count up.  So, i = 2 in the second iteration of the loop.  It continues to loop until the last number in the loop is reached.

By default, 1 is added to the variable counter for each iteration in the loop.  This is called the Step Value, and we can control the value of each step in the counter.  The Step value is added to the end of the For line.  The following line will add 2 to the counter for each iteration in the loop.

For i = 2 To 20 Step 2

If you wanted to shade every other row in a sheet, you might use a loop like this.

For Next Loop Step Counter Banded Rows Example Excel VBA

Looping Backwards

We can also use the Step Value to loop backwards by specifying a negative number.

For i = 100 To 1 Step -1

Notice that the Start Value is now the larger number and the End Value is the smaller number.  The loops starts at 100 (Start Value) and subtracts 1 from the counter variable (Step -1) for each iteration in the loop until it gets to 1 (End Value).

The Step keyword is optional.  If you do not specify it then VBA assumes a Step value of 1.

Looping backwards is great if you are deleting items.  I will write a separate post on this, but the general idea is that when we are looping through a collection and deleting items, the size of the collection gets smaller as items are deleted.  The loop will typically hit an error once it gets to the 10th item, when there are now only 9 items in the collection.  Looping backwards prevents this potential error.

Exiting the Loop Early

Typically the loop will iterate through all items in the collection, then continue on to the next line of code below the Next line.  However, we can stop the loop early with an Exit For statement.

Exit For

The following macro uses the Exit For statement to exit the loop after the first sheet that starts with the word “Report” is found an unhidden.

Sub Unhide_First_Sheet_Exit_For()
'Unhides the first sheet that contain a specific phrase
'in the sheet name, then exits the loop.

Dim ws As Worksheet
    
    For Each ws In ActiveWorkbook.Worksheets
    
        'Find the sheet that starts with the word "Report"
        If Left(ws.Name, 6) = "Report" Then
            
            ws.Visible = xlSheetVisible
            
            'Exit the loop after the first sheet is found
            Exit For
        
        End If
    Next ws

End Sub

The ws variable retains the reference to the worksheet after the loop is exited early, and can be used again in the code below the loop.

Variable Reference Is Not Reset When VBA For Next Loop Exit Early

Variable Not Required After Next Keyword

You might have noticed that I added the variable after the Next keyword at the bottom of the loop in the examples above.

Next ws
Next i

This is NOT required, and you might not see it in other examples you find on the web. However, I like to include the variable after Next for two reasons.

  1. We can use it when debugging code to see the value of the variable by hovering the mouse over the variable when the code is stopped.
  2. It makes it easier to understand which For line the Next line is connected to. This is especially true when you have multiple loops or nested loops in your macros.

Variable After Next is Not Required in For Next Loop

Therefore, I recommend adding the variable after the Next keyword as a best practice.  A little extra work up front will save time & headache in the future.  Trust me! 😉

Macro Code Examples of VBA For Loops

Here are additional articles with macros that use at least one For Next Loop.

3 Ways to Unhide Multiple Sheets in Excel + VBA Tutorial

Automatic Default Number Formatting in Excel Pivot Tables

3 Tips to Save and Close All Open Excel Workbook Files + Macro

The SUBTOTAL Metrics Macro – Create a Summary Table of All Function Types

How to Add a Table of Contents Image Gallery Sheet to Your Excel Files

Hide & Unhide (Filter) Columns with a Slicer or Filter Drop-down Menu

Filter a Pivot Table or Slicer for the Most Recent Date or Period

How to Make Your Excel Dashboards Resize for Different Screen Sizes

Convert Pivot Table to SUMIFS Formulas + Free VBA Macro

VBA Macro to Hide All Columns That Contain a Value in a Cell

How to Repeat Tasks with VBA Code – Looping – Great article with lots of examples from my friend Chris Newman at The Spreadsheet Guru.

What Task Do You Want To Loop?

I hope that article helps get you started with loops.  Don’t forget to download the free Excel file that contains the code samples.

Loops are definitely an intermediate coding technique that force us to go beyond the macro recorder.  Unfortunately, the macro recorded cannot create loops.  However, this is a skill that you will be able to use over and over again throughout your career to automate simple and complex tasks.  Understanding how to use loops will give you magical powers with Excel.

Please leave a comment below with a task that you want to automate with a loop.  Thank you! 🙂

Key Points

  • VBA For Loops are fixed types of loops.
  • It is not possible to use any of these loops while recording a macro.

VBA FOR NEXT is a fixed loop that uses a counter to run iterations. In simple words, you need to specify the number of times you want to run the loop, and once it reaches that count loop, it will stop automatically. That’s why it is a fixed loop and most popular among VBA developers.

Syntax

Following is the syntax for the VBA For Next Loop:

For counter = Start To End [Step stepsize]
[statements]
Next [counter]
  1. Counter: It’s variable that stores the count of the repetition and increases its value with each repetition. For example, if the loop is in its fifth repetition the value of the counter will be five, and once the loop executes the statement for the fifth iteration the value of the counter changes to six.
  2. Start: It is a numeric variable that stores the starting value for the counter.
  3. End: It is a numeric variable that stores the ending value for the counter.
  4. Step Size: This variable specifies a big increase or decrease in the value of the counter. By default, the step size is one, but you can also use any positive or negative value.
  5. Statement: It’s a set of code do you want to execute in each iteration of the For Next loop.
  6. Next: It’s the end statement for one iteration of the loop and uses the counter value to tell VBA to repeat the loop and once the counter reaches the end value it ends the loop.

Example to Understand For Next Loop

To understand how to use it for the next loop, let’s write a simple code to add serial numbers in a column.

Let me elaborate a little more: We need to write a code that can go from cell selected cell to the next 10 cells one by one and add serial numbers just in the below snapshot.

To use For Next Loop, you can use the following steps:

  1. First, you need to declare a variable that you can use to store the counter value.
    3-declare-a-variable
  2. Next, we need to assign the counter value to the variable.
    4-assign-the-counter-value
  3. Now it’s time to write code for loop, so in the first line, you need to use the counter variable and define starting and the ending value. Here in this code, you have the variable “i” as the ending value.
    5-write-code-for-loop
  4. From here you need to write code that can add the serial numbers into the active cell and then move to the next cell. As the counter value increases in each iteration, you can use it to enter the serial number into the active cell and after that, you can use the offset to move the selection to the next cell downwards.
    6-code-that-can-add-serial-number
  5. In the end, use the keyword next and the counter variable to end the code for the loop.
Sub AddSerialNumbers()
Dim i As Integer
i = 10 

    For i = 1 To i 
  
        ActiveCell.Value = i       
        ActiveCell.Offset(1, 0).Activate  
 
    Next i

End Sub

You can see in the below snapshot, when I run this code it starts from the selected cell by entering a serial number and then moves to the next cell with each iteration.

As you know, For Next is a fixed loop and in this code, when you assign a numeric value, it tells VBA to run the loop for that number of times.

And you can see the below snapshot that I have taken in the second iteration of the loop where the value of “i” counter variable is two.

The point I’m trying to make is the counting variable changes its value in each iteration and enters that value in the active cell and then offset activates the next cell downward that completing one iteration.

In the end, the “Next” keyword it’s VBA to go back to the first line of the loop and repeat it. As you have seen in the syntax of For Next, you can also use a step value in the loop to make the counter work according to that.

So if you use two as a step value the code would be something like the below.

Sub AddSerialNumbers()

Dim i As Integer
i = 10 

    For i = 1 To i Step 2  

        ActiveCell.Value = i
        ActiveCell.Offset(1, 0).Activate 
  
    Next i

End Sub

And when you run this code, it will on the activity something like the below snapshot.

When you use a step value (Like, Step 2, that you have used in the above code), VBA skips every 2nd iteration in the loop, and as you can see you have got five numbers with the difference of one within each number.

Note: In the above example, you have used “i” as the counter variable, but you can use a different name as well according to your convenience.

For Each Next Loop

VBA FOR EACH NEXT is a fixed loop that can loop through all the objects in a collection. In the For Each Next, you don’t need to specify the count of iterations. Instead, you can specify a collection of objects, and it will be able to loop through all those objects one by one.

For Example: If you want to loop through all the cells from a range. In this case, the range is the collection, and cells are the objects that you have.

Syntax

Following is the syntax for the VBA For Each Next Loop:

For Each Object In Collection
[statements]
Next [object]
  1. Object: It represents the one object in the collection of objects in which you are looping. With each iteration, moves from one object to the next.
  2. Collection: It’s a collection of objects in which you want to loop.
  3. Statement: Line(s) of code that you want to execute in each loop through all the objects in the collection.
  4. Next: It’s the end statement for one iteration of the loop and tells VBA to move to the next object in the collection.

Example to Understand the For Each Next Loop

To understand For Each Next loop, let’s write a code to hide all the sheets other than the active worksheet. This code will check each worksheet’s name and match it with the active worksheet’s name and hide it if it doesn’t match.

To use For Each Next loop, you can use the following steps:

  1. First, you need to declare a variable to use as a worksheet.
    10-code-to-hide-the-all-sheets
  2. After that, use “For each” keyword, and then “mySheet” variable for the sheet, and use “ActiveWorkbook.Worksheets” for the collection of worksheets from the active workbook.
    11-for-each-mysheet-active-workbook-worsheets
  3. Next, you need to use VBA IF Statement to test if the name of the sheet that is currently in that loop iteration is NOT EQUAL to the active worksheet, and if this condition is true then hide sheet that is now in the loop iteration.
    12-vba-if-statement-to-test
  4. In the end, you have the NEXT keyword and “mySheet” the variable to end the code for the loop.
    13-next-keyword-and-mysheet

Final Code:

Sub Hide_Other_Sheets()
 
Dim mySheet As Worksheet
 
For Each mySheet In ActiveWorkbook.Worksheets

    If mySheet.Name <> ActiveSheet.Name Then

        mySheet.Visible = False

    End If

Next mySheet

End Sub

When you run this code, it will loop through each worksheet in the active workbook and match its name with the active worksheet, and if the worksheet’s name is not matched with the active worksheet’s name, it will hide it.

In this way, all the worksheets will hide.

vba цикл excel for each for next

Цикл For Loop в VBA – один из самых популярных циклов в Excel. Данный цикл имеет две формы – For Next и For Each In Next. Данные операторы используются для последовательного  перемещения по списку элементов или чисел. Для завершения цикла мы можем в любой момент использовать команду выхода. Давайте подробнее рассмотрим каждый из этих циклов.

Цикл For Next имеет следующий синтаксис:

1
2
3

For счетчик = начало_счетчика To конец_счетчика
‘Какое-то действие
Next счетчик

То что мы делаем здесь, по существу, это создаем цикл, который использует переменную счетчик как хранитель времени. Устанавливаем его значение равным начало_счетчика, и увеличиваем (или уменьшаем) на 1 во время каждого витка. Цикл будет выполняться до тех пор, пока значение счетчик не станет равным конец_счетчика. Когда оба эти значения совпадут, цикл выполнится последний раз и остановится.

Пример цикла

1
2
3
4
5
6

Sub пример_цикла1()
For счетчик = 1 to 10
j = счетчик
Next счетчик
msgbox «Значение счетчика на последнем витке равно  « &amp; счетчик
End Sub

Последнее значение переменной счетчик будет равным 11

VBA обратный цикл For Loop с инструкцией STEP

Если у вас появилась необходимость перемещаться от большего значения к меньшему – вы можете использовать цикл в обратном направлении. Вот пример обратного цикла:

1
2
3
4
5
6

Sub пример_цикла2()
For счетчик = 10 to 1 Step -1
j = счетчик
Next счетчик
msgbox «Значение счетчика на последнем витке равно  « &amp; счетчик
End Sub

Последнее значение переменной счетчик будет равным 1.

Как вы могли заметить, мы можем использовать инструкцию Step n для работы цикла как  вперед, так  и в обратном направлении. По умолчанию значение Step равно 1, но оно может быть изменено, если необходимо пропускать какие-либо значения, тогда значение n будет больше одного, или перемещаться в обратном направлении, тогда n будет отрицательным.

VBA цикл For Each … Next

Цикл For Each … Next имеет следующий цикл:

1
2
3

For Each элемент_группы In группа_элементов
‘Какое-то действие
Next элемент_группы

Здесь переменная элемент_группы принадлежит к группе_элементов (железная логика!!!). Я имею в виду, что объект группа_элементов должен быть коллекцией объектов. Вы не сможете запустить цикл For Each для отдельно объекта (Microsoft сразу оповестит вас об этом 438-й ошибкой).

vba циклы excel for each for next

Данный цикл перебирает все элементы какой-либо коллекции, начиная с самого первого. Вы можете использовать данный цикл, если вам необходимо, например, обойти все листы в книге, объекты на листе, сводные таблицы и т.д.

Ниже представлен пример, как можно воспользоваться циклом For Each для просмотра всех листов книги:

1
2
3
4
5

Sub пример_цикла4()
For Each sht In ActiveWorkbook.Worksheets
MsgBox sht.Name
Next sht
End Sub

… либо всех сводных таблиц на листе

1
2
3
4
5

Sub пример_цикла()
For Each pvt In ActiveSheet.PivotTables
MsgBox pvt.Name
Next pvt
End Sub

Прерывание  цикла VBA

Если вам необходимо выйти из цикла до момента, как будет достигнуто условие завершения цикла, воспользуйтесь командой End For в связке с инструкцией IF. В примере, приведенном ниже, мы выйдем из цикла до момента достижения условия завершения, в данном цикле выход будет осуществлен при условии, когда переменная счетчик будет  равна 3.

1
2
3
4
5
6

Sub пример_цикла5()
For счетчик  = 0 To 5
MsgBox счетчик
If (счетчик = 3) Then Exit For
Next счетчик
End Sub

Пропуск части цикла в For Each

Пропускать часть цикла, а затем возвращаться назад – плохая практика. Тем не менее, давайте рассмотрим пример:

1
2
3
4
5
6
7
8
9
10
11
12

Sub пример_цикла6 ()
Dim j As Integer
For i = 0 To 5
b:
If (j = 3) Then GoTo a:
j = i
Next i
a:
j = 4
GoTo b:
MsgBox («Значение  j = « &amp; j)
End Sub

Здесь мы пропустили одну итерацию (когда j = 3). Как вы думаете, какой результат выдаст программа? 3? 5? Ну… на самом деле, ни один из вариантов не верный. Цикл будет выполняться бесконечно, пока память компьютера не переполнится.

Однако возможность пропустить шаг цикла без последствий существует. Вы можете увеличить значение счетчика на 1 (или другое значение), что приведет к пропуску операций, находящихся между этими значениями. Вот пример:

1
2
3
4
5
6

Sub пример_цикла7()
For i = 0 To 5
i = i + 1
MsgBox i
Next i
End Sub

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

This post provides a complete guide to the standard VBA For Loop and the VBA For Each Loop.

If you are looking for information about the VBA While and VBA Do Loop then go here.

If you want some quick info about the For loops then check out the Quick Guide table in the section below.

If you are looking for information on a particular topic then check out the Table of Contents below.

“History is about loops and continuums” – Mike Bidlo.
 

Related Links for the VBA For Loop

The Complete Guide to Ranges in Excel VBA.
The Complete Guide to Copying Data in Excel VBA.
VBA Do While Loop.

A Quick Guide to the VBA For Loop

Loop format Description Example
For … Next Run 10 times For i = 1 To 10
Next
For … Next Run 5 times. i=2,4, 6 etc. For i = 2 To 10 Step 2
Next
For … Next Run in reverse order For i = 10 To 1 Step -1
    Debug.Print i
Next
For … Next Go through Collection For i = 1 To coll.Count
    Debug.Print coll(i)
Next
For … Next Go through array For i = LBound(arr) To UBound(arr)
    Debug.Print arr(i)
Next i
For … Next Go through 2D array For i = LBound(arr) To UBound(arr)
    For j = LBound(arr,2) To UBound(arr,2)
        Debug.Print arr(i, j)
    Next j
Next i
For Each … Next Go through Collection Dim item As Variant
For Each item In coll
    Debug.Print item
Next item
For Each … Next Go through array Dim item As Variant
For Each item In arr
    Debug.Print item
Next item
For Each … Next Go through 2D array Dim item As Variant
For Each item In arr
    Debug.Print item
Next item
For Each … Next Go through Dictionary Dim key As Variant
For Each key In dict.Keys
    Debug.Print key, dict(key)
Next key
Both types Exit Loop For i = 1 To 10
    If Cells(i,1) = «found» Then
        Exit For
    End If
Next i

The VBA For Loop Webinar

If you are a member of the website, click on the image below to view the webinar for this post.

(Note: Website members have access to the full webinar archive.)

Introduction to the VBA For Loop

Loops are by far the most powerful component of VBA. They are the rocket fuel of your Macros. They can perform tasks in milliseconds that would take humans hours. They also dramatically reduce the lines of code your applications need.

For Loops have been part of all major programming languages since they were first used with Fortan in 1957.

If you have never used loops before then this post is a great place to start. It provides an in-depth guide to loops, written in plain English without the jargon.

Let’s start with a very important question – what are loops and why do we need them?

What are VBA For Loops?

A loop is simply a way of running the same lines of code a number of times. Obviously running the same code over and over would give the same result.

So what is important to understand is that the lines of code normally contain a variable that changes slightly each time the loop runs.

For example, a loop could write to cell A1, then cell A2, A3 and so on. The slight change each time is the row.

Let’s look at a simple example.

VBA For Loop Example 1

 
The following code  prints the values 1 to 5 in the Immediate Window(Ctrl + G to view).

Debug.Print 1
Debug.Print 2
Debug.Print 3
Debug.Print 4
Debug.Print 5

The Immediate Window

If you have not used the Immediate Window before then this section will get you up to speed quickly.

The function Debug.Print writes values to the Immediate  Window. To view this window select View->Immediate Window from the menu( the shortcut is Ctrl + G)

 
ImmediateWindow

 
ImmediateSampeText

VBA For Loop Example 2

Now imagine we want to print out the numbers 1 to 20. We would need to add 15 more lines to the example above.

 
However, using a loop we only need to write Debug.Print once.

    For i = 1 To 20
        Debug.Print i
    Next i

 
The output is:

VBA Excel

Output

 
If we needed print the numbers 1 to 1000 then we only need to change the 20 to 1000.

Normally when we write code we would use a variable instead of a number like 20 or 1000. This gives you greater flexibility. It allows you to decide the number of times you wish to run the loop when the code is running. The following example explains this.

VBA For Loop Example 3

A common task in Excel is read all the rows with with data. 

 
The way you approach this task is as follows

  1. Find the last row with data
  2. Store the value in variable
  3. Use the variable to determine how many times the loop runs

 
Using a variable in the loop makes your code very flexible. Your will work no matter how many rows there are.

Let’s have a look at an example. Imagine you receive a sheet with a list of fruit types and their daily sales. You want to count the number of Oranges sold and this list will vary in size depending on sales.

 
The following screenshot shows an example of this list

Sample Data of Fruit Sales

Sample Data of Fruit Sales

 
We can use the code to count the oranges

' https://excelmacromastery.com/
Sub CountFruit()

    ' Get the last row with text
    Dim LastRow As Long
    LastRow = Sheet1.Cells(Sheet1.Rows.Count, 1).End(xlUp).Row

    Dim i As Long, Total As Long
    ' Use LastRow in loop
    For i = 2 To LastRow
        ' Check if cell has text "Orange"
        If Sheet1.Cells(i, 1).Value = "Oranges" Then
            ' Add value in column B to total
            Total = Total + Sheet1.Cells(i, 2).Value
        End If
    Next i

    ' Print total
    Debug.Print "Total oranges sold was:"; Total

End Sub

 
You can try this code for yourself. Change the number of fruit items and you will see that the code still works fine.

If you were to increase the number fruit items to a large value like 10,000 then you will hardly notice the difference in the time it takes to run – almost instantly.

Loops are super fast. This is what makes them so powerful. Imagine performing a manual task on 10,000 cells. It would take a considerable amount of time.

Advantages of the VBA For Loop

4To conclude this section we will list the major advantages of using loops

  • They reduce the lines code you need
  • They are flexible
  • They are fast

 
In the next sections we will look at the different types of loops and how to use them.

The Standard VBA For Loop

The VBA For loop is the most common loop you will use in Excel VBA. The For Loop is used when you can determine the number of times it will be run. For example, if you want to repeat something twenty times.

YouTube Video For Loop

Check out this YouTube Video of the For Loop:

Get the workbook and code for this video here
 

Format of the Standard VBA For Loop

The Standard VBA For Loop has the following format:

For <variable> = <start value> to <end value>
Next <variable>

The start and end values can be variables. Also the variable after Next is optional but it is useful and it makes it clear which for loop it belongs to.

How a For Loop Works

Let’s look at a simple for loop that prints the numbers 1 to 3

    Dim i As Long
    For i = 1 To 3
        Debug.Print i
    Next i

 
How this code works is as follows

i is set to 1
The value of i(now 1) is printed

 
i is set to 2
The value of i(now 2) is printed

 
i is set to 3
The value of i(now 3) is printed

 
If we did not use a loop then the equivalent code would be

    Dim i As Long
    i = i + 1
    Debug.Print i
    i = i + 1
    Debug.Print i
    i = i + 1
    Debug.Print i

 
The i = i + 1 line is used to add 1 to i and is a common way in programming to update a counter.

Using Step with the VBA For Loop

You can see that i is increased by one each time. This is the default. You can specify this interval using Step keyword.

 
The next example shows you how to do this:

    ' Prints the even numbers i.e. 2,4,6,8 ... 20
    For i = 2 To 20 Step 2
        Debug.Print i
    Next i

 
You can use a negative number with Step which will count in reverse

    ' Prints the even numbers in reverse i.e. 20,18,16,14 ... 2
    For i = 20 To 2 Step -2
        Debug.Print i
    Next i

 
Note: if Step is positive then your starting number must be lower than you ending number. The following loop will not run because the starting number 20 is greater than 10. VBA therefore, thinks it has already reached the target value 10.

    ' Will not run as starting number already greater than 10
    For i = 20 To 10 Step 1
        Debug.Print i
    Next i

 
If Step is negative then the start number must be greater than the end number.

Exit the For Loop

Sometimes you may want to leave the loop earlier if a certain condition occurs. For example if you read bad data.

 
You can use Exit For to automatically leave  the loop as shown in the following code

    For i = 1 To 1000

        ' If cell is blank then exit for
        If Cells(i, 1) = "" Then
            MsgBox "Blank Cell found - Data error"
            Exit For
        End If

    Next i

Using the VBA For Loop with a Collection

The For loop can also be used to read items in a Collection.

 
In the following example, we display the name of all the open workbooks

    Dim i As Long
    For i = 1 To Workbooks.Count
        Debug.Print Workbooks(i).FullName
    Next i

Using Nested For Loops

Sometimes you may want to use a loop within a loop. An example of this would be where you want to print the names of the worksheets of each open workbook.

The first loop would go through each workbook. Each time this loop runs it would use a second loop to go through all the worksheets of that workbook. It is actually much easier to do than it sounds.

 
The following code shows how:

' https://excelmacromastery.com/
Sub ListWorksheets()

    Dim i As Long, j As Long
    ' First Loop goes through all workbooks
    For i = 1 To Workbooks.Count

        ' Second loop goes through all the worksheets of workbook(i)
        For j = 1 To Workbooks(i).Worksheets.Count
            Debug.Print Workbooks(i).Name + ":" + Worksheets(j).Name
        Next j

    Next i

End Sub

 
This works as follows:

 
The first loop sets i to 1

 
The second loop then uses the workbook at 1 to go through the worksheets.

 
The first loop sets i to 2

 
The second loop then uses the workbook at 2 to go through the worksheets.

 
and so on

 
It the next section we will use a For Each loop to perform the same task. You will find the For Each version much easier to read.

The VBA For Each Loop

The VBA For Each loop is used to read items from a collection or an array. We can use the For Each loop to access all the open workbooks. This is because Application.Workbooks is a collection of open workbooks.

 
This is a simple example of using the For Each Loop

    Dim wk As Workbook
    For Each wk In Workbooks
        Debug.Print wk.FullName
    Next wk

 Format of the VBA For Each Loop

You can see the format of the VBA for each loop here(See Microsoft For Each Next documentation):
For Each <variable> in <collection>
Next <variable>

To create a For Each loop we need a variable of the same type that the collection holds. In the example here we created a variable of type Workbook.

If the collection has different types of items we can declare the variable as a variant.

VBA contains a collection called Sheets. This is a collection of sheets of type Worksheet(normal) and Chart(when you move a chart to be a full sheet). To go through this collection you would declare the variable as a Variant.

 
The following code uses For Each to print out the name of all the sheets in the current workbook

    Dim sh As Variant
    For Each sh In ThisWorkbook.Sheets
        Debug.Print sh.Name
    Next sh

Order of Items in the For Loop

For Each goes through items in one way only.

For example, if you go through all the worksheets in a workbook it will always go through from left to right. If you go through a range it will start at the lowest cell e.g. Range(“A1:A10”) will return A1,A2,A3 etc.

This means if you want any other order then you need to use the For loop.

 
Both loops in the following example will read the worksheets from left to right:

    ' Both loops read the worksheets from left to right
    Dim wk As Worksheet
    For Each wk In ThisWorkbook.Worksheets
        Debug.Print wk.Name
    Next

    Dim i As Long
    For i = 1 To ThisWorkbook.Worksheets.Count
        Debug.Print ThisWorkbook.Worksheets(i).Name
    Next

 
As you can see the For Each loop is neater to write. However if you want to read the sheets in any other order e.g. right to left then you have to use the for loop:

    ' Reading the worksheets from right to left
    Dim i As Long
    For i = ThisWorkbook.Worksheets.Count To 1 Step -1
        Debug.Print ThisWorkbook.Worksheets(i).Name
    Next

Using the VBA For Each Loop With Arrays

One thing to keep in my is that the For Each loop is that it is read-only when you use it with arrays.

 
The following example demonstrates this:

' https://excelmacromastery.com/
Sub UseForEach()

    ' Create array and add three values
    Dim arr() As Variant
    arr = Array("A", "B", "C")

    Dim s As Variant
    For Each s In arr
        ' Changes what s is referring to - not value of array item
        s = "Z"
    Next

    ' Print items to show the array has remained unchanged
    For Each s In arr
        Debug.Print s
    Next

End Sub

 
In the first loop we try to assign s to “Z”. When happens is that s is now referring the string “Z” and no longer to the item in the array.

In the second loop we print out the array and you can see that none of the values have changed.

 
When we use the For Loop we can change the array item. If we change the previous code to use the For Loop you it will change all the array values to “Z”

' https://excelmacromastery.com/
Sub UsingForWithArray()

    ' Create array and add three values
    Dim arr() As Variant
    arr = Array("A", "B", "C")

    Dim i As Long
    For i = LBound(arr) To UBound(arr)
        ' Changes value at position to Z
        arr(i) = "Z"
    Next

    ' Print items to show the array values have change
    For i = LBound(arr) To UBound(arr)
        Debug.Print arr(i)
    Next

End Sub

If your Collection is storing Objects the you can change the items using a For Each loop.

Using Nested For Each Loops

We saw already that you can have a loop inside other loops. Here is the example from above:

' https://excelmacromastery.com/
Sub ListWorksheets()

    Dim i As Long, j As Long
    ' First Loop goes through all workbooks
    For i = 1 To Workbooks.Count

        ' Second loop goes through all the worksheets of workbook(i)
        For j = 1 To Workbooks(i).Worksheets.Count
            Debug.Print Workbooks(i).Name + ":" + Worksheets(j).Name
        Next j

    Next i

End Sub

This time we will use the For Each loop to perform the same task:

' https://excelmacromastery.com/
Sub ReadAllWorksheets()

    Dim wk As Workbook, sh As Worksheet
    ' Read each workbook
    For Each wk In Workbooks

        ' Read each worksheet in the wk workbook
        For Each sh In wk.Worksheets
            ' Print workbook name and worksheet name
            Debug.Print wk.Name + ": " + sh.Name
        Next sh

    Next wk

End Sub

As you can see this is a neater way of performing this task than using the For Loop:

This code run as follows:

  1. Get the first Workbook from the Workbooks collection
  2. Go through all the worksheets in this workbook
  3. Print the workbook/worksheet details
  4. Get the next workbooks in the collection
  5. Repeat steps 2 to 3
  6. Continue until no more workbooks are left in the collection

How to Loop Through a Range

In Excel VBA, the most common use of a For Loop is to read through a range.

Imagine we have the data set in the screenshot below. Our task is to write code that will read through the data and copy the amounts to the column J. We are only going to copy amounts that are greater than 200,000.

VBA For Loop Range

 
The following example shows how we do it:

' Read through an Excel Range using the VBA For Loop
' https://excelmacromastery.com/
Sub ForLoopThroughRange()

    ' Get the worksheet
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Worksheets("Sheet1")
    
    ' Get the Range
    Dim rg As Range
    Set rg = sh.Range("A1").CurrentRegion
    
    ' Delete existing output
    sh.Range("J1").CurrentRegion.ClearContents
    
    ' Set the first output row
    Dim row As Long
    row = 1
    
    ' Read through all the rows using the For Loop
    Dim i As Long
    For i = 2 To rg.Rows.Count
    
        ' Check if amount is greater than 200000
        If rg.Cells(i, 4).Value > 200000 Then
        
            ' Copy amount to column m
            sh.Cells(row, "J").Value = rg.Cells(i, 4).Value
            
            ' Move to next output row
            row = row + 1
            
        End If
        
    Next i
    
End Sub

 
This is a very basic example of copying data using Excel VBA. If you want a complete guide to copying data using Excel VBA then check out this post

Summary of the VBA For Loops

The Standard VBA For Loop

  • The For  loop is slower than the For  Each loop.
  • The For loop can go through a selection of items e.g. 5 to 10.
  • The For loop can read items in reverse e.g. 10 to 1.
  • The For loop is not as neat to write as the For Each Loop especially with nested loops.
  • To exit a For loop use Exit For.

The VBA For Each Loop

  • The For Each loop is faster than the For loop.
  • The For Each loop goes through all items in the collectionarray.
  • The For Each loop can go through items in one order only.
  • The For Each loop is neater to write than a For Loop especially for nested loops.
  • To exit a For Each loop use Exit For.

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

Понравилась статья? Поделить с друзьями:
  • Excel vba objects and methods
  • Excel vba items in combobox
  • Excel vba object module
  • Excel vba isnumber vba
  • Excel vba is value in array