Функция for vba word

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

Содержание:

  • for цикл
  • Синтаксис
  • Диаграмма потока
  • пример
  • for … loop
  • Синтаксис
  • пример
  • while..wend loop
  • Синтаксис
  • Диаграмма потока
  • пример
  • Цикл do..while
  • Синтаксис
  • Диаграмма потока
  • пример
  • Альтернативный синтаксис
  • пример
  • do..intil loop
  • Синтаксис
  • Диаграмма потока
  • пример
  • Альтернативный синтаксис
  • Диаграмма потока
  • пример
  • Записи управления циклом
  • Контрольное заявление и описание
  • Выход для оператора
  • Синтаксис
  • Диаграмма потока
  • пример
  • Exit Do
  • Синтаксис
  • пример

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

Оператор цикла позволяет нам выполнять оператор или группу операторов несколько раз. Ниже приведен общий вид оператора цикла в VBA.

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

Цикл for — это структура управления повторением, которая позволяет разработчику эффективно писать цикл, который необходимо выполнить определенное количество раз.

Синтаксис

Ниже приведен синтаксис цикла for в VBA.

For counter = start To end [Step stepcount]
   [statement 1]
   [statement 2]
   ....
   [statement n]
   [Exit For]
   [statement 11]
   [statement 22]
   ....
   [statement n]
Next

Диаграмма потока

Работа с циклами в VBA:loop, for each, for next

Ниже приведен поток управления в режиме Loop —

  • Первый шаг выполняется. Этот шаг позволяет инициализировать любые переменные управления контурами и увеличивать переменную счетчика шагов.
  • Во-вторых, условие оценивается. Если это правда, выполняется тело цикла. Если оно ложно, тело цикла не выполняется, и поток управления переходит к следующему оператору сразу после цикла For.
  • После выполнения цикла цикла For поток управления переходит к следующему оператору. Этот оператор позволяет вам обновлять любые переменные управления циклом. Он обновляется на основе значения счетчика шагов.
  • Условие теперь оценивается снова. Если это правда, цикл выполняется, и процесс повторяется (тело цикла, затем увеличивают шаг, а затем снова условие). После того, как условие становится ложным, цикл For заканчивается.

пример

Добавьте кнопку и добавьте следующую функцию.

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

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

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

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

for … loop

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

Для каждого цикла аналогичен For Loop; однако цикл выполняется для каждого элемента в массиве или группе. Следовательно, счетчик шагов не будет существовать в этом типе цикла. Он в основном используется с массивами или используется в контексте объектов файловой системы, чтобы работать рекурсивно.

Синтаксис

Ниже приведен синтаксис цикла For Each в VBA.

For Each element In Group
   [statement 1]
   [statement 2]
   ....
   [statement n]
   [Exit For]
   [statement 11]
   [statement 22]
Next

пример

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

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

apple
orange
cherries

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

while..wend loop

В цикле While While … Wend , если условие равно True, все операторы выполняются до тех пор, пока не встретится ключевое слово Wend.

Если условие ложно, цикл завершается, и элемент управления переходит к следующему оператору после ключевого слова Wend .

Синтаксис

Ниже приведен синтаксис цикла While..Wend в VBA.

While condition(s)
   [statements 1]
   [statements 2]
   ...
   [statements n]
Wend

Диаграмма потока

Работа с циклами в VBA:loop, for each, for next

пример

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

Когда вышеуказанный код выполняется, он выводит следующее в поле сообщения.

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

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

Цикл do..while

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

Синтаксис

Ниже приведен синтаксис цикла Do … While в VBA.

Do While condition
   [statement 1]
   [statement 2]
   ...
   [statement n]
   [Exit Do]
   [statement 1]
   [statement 2]
   ...
   [statement n]
Loop           

Диаграмма потока

Работа с циклами в VBA:loop, for each, for next

пример

В следующем примере используется цикл Do … while для проверки состояния в начале цикла. Операторы внутри цикла выполняются, только если условие становится True.

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

Когда выполняется вышеуказанный код, он печатает следующий вывод в окне сообщения.

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

Альтернативный синтаксис

Существует также альтернативный синтаксис для Do … while loop, который проверяет состояние в конце цикла. Основное различие между этими двумя синтаксисами объясняется в следующем примере.

Do 
   [statement 1]
   [statement 2]
   ...
   [statement n]
   [Exit Do]
   [statement 1]
   [statement 2]
   ...
   [statement n]
Loop While condition

пример

В следующем примере используется цикл Do … while для проверки состояния в конце цикла. Заявления внутри цикла выполняются хотя бы один раз, даже если условие False.

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

Когда выполняется вышеуказанный код, он печатает следующий вывод в окне сообщения.

The value of i is : 11

Операторы do..While будут выполняться до тех пор, пока условие равно True. (Т. Е.) Петля должна повторяться до тех пор, пока условие не будет False.

do..intil loop

Do … intil цикл не будет использован, когда мы хотим повторить набор операторов, пока условие ложно. Условие может быть проверено в начале цикла или в конце цикла.

Синтаксис

Ниже приведен синтаксис цикла Do..Until в VBA.

Do Until condition
   [statement 1]
   [statement 2]
   ...
   [statement n]
   [Exit Do]
   [statement 1]
   [statement 2]
   ...
   [statement n]
Loop    

Диаграмма потока

Работа с циклами в VBA:loop, for each, for next

пример

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

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

Когда выполняется вышеуказанный код, он печатает следующий вывод в окне сообщения.

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

Альтернативный синтаксис

Существует также альтернативный синтаксис Do … До цикла, который проверяет условие в конце цикла. Основное различие между этими двумя синтаксисами объясняется следующим примером.

Do 
   [statement 1]
   [statement 2]
   ...
   [statement n]
   [Exit Do]
   [statement 1]
   [statement 2]
   ...
   [statement n]
Loop Until condition

Диаграмма потока

Работа с циклами в VBA:loop, for each, for next

пример

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

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

Когда выполняется вышеуказанный код, он печатает следующий вывод в окне сообщения.

The value of i is : 11

Операторы do..Until будут выполняться до тех пор, пока условие False. (Т. Е.) Петля должна повторяться до тех пор, пока условие не будет истинным.

Записи управления циклом

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

Контрольное заявление и описание

Выход для оператора

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

Синтаксис

Ниже приведен синтаксис Exit For Statement в VBA.

Диаграмма потока

Работа с циклами в VBA:loop, for each, for next

пример

В следующем примере используется Exit For . Если значение счетчика достигает 4, цикл For Loop завершается, и управление переходит к следующему утверждению сразу после цикла For Loop.

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

Когда вышеуказанный код выполняется, он печатает следующий вывод в окне сообщений.

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

Завершает оператор цикла For и передает выполнение в оператор сразу после цикла

Exit Do

Exit Do Заявление используется , когда мы хотим , чтобы выйти из Do Loops на основе определенных критериев. Он может использоваться как в Do Do … While, так и Do … До циклов.

Когда Exit Do выполняется, управление переходит к следующему оператору сразу после Do Loop.

Синтаксис

Ниже приведен синтаксис выражения Exit Do в VBA.

пример

В следующем примере используется Exit Do . Если значение счетчика достигает 10, выходная линия Do завершается, и управление переходит к следующему оператору сразу после цикла For Loop.

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

Когда выполняется вышеуказанный код, он печатает следующий вывод в окне сообщения.

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

Завершает оператор Do While и передает выполнение в оператор сразу после цикла

 С уважением, авторы сайта Компьютерапия

Понравилась статья? Поделитесь ею с друзьями и напишите отзыв в комментариях!

Доброго времени суток! Данную статью я решил посвятить рубрике по основам программирования в Visual Basic for Application. И сегодня мы поговорим о циклах в VBA, разберём их синтаксис и рассмотрим несколько примеров, которые часто встречаются программисту.

Сначала напомню, что цикл — процесс повторения части кода, выполняемый, пока не будет выполнено или нарушено заданное нами условие.

В данной статье мы разберём синтаксис и примеры следующих циклов в VBA:

  • For
  • For each
  • While
  • Until

Цикл For в VBA

Блок схема цикла for
Цикл for в VBA обычно используется при зацикливании фрагмента кода, если нам известно конечное значение counter — счетчика, при котором мы выйдем из цикла.
Возьмём для примера самый распространённый пример:

Сгенерировать массив из 5 целых значений

Dim mas(5) As Integer
For i% = 0 To 4
    mas(i) = Int((10 * Rnd) + 1)
Next i

Обратите ваше внимание, что в этом примере используется неявное объявление при работе с циклами в VBA. i% — означает неявное объявление переменной i в формате integer. Такая конструкция по сути заменяет следующую: dim i as integer. Это используется для сокращения кода и для удобства написания и чтения. В старых версиях VBA необходимо указывать знак формата после каждого использования неявной переменной. В более поздних версиях достаточно всего один раз.

VBA для цикла for даёт возможность использовать функцию Step. Как ясно из перевода, это шаг, с которым мы будем проходить наш интервал. По умолчанию, он равен 1. Популярный вариант использования встречается в случаях, когда counter связан с переменной, используемой внутри цикла. Например, при написании программ, связанных с функциями.

Найти пересечение графика функции y = 5*x + 5 с осью ординат

Function expr(x As Integer) As Integer
    expr = 5 * x + 5
End Function
Sub CodeTown()
    Dim i As Integer
    For i = -10 To 10 Step 1
        If expr(i) = 0 Then MsgBox "При Y = 0, Х = "+ CStr(i)
    Next i
End Sub

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

Function expr(x As Integer) As Integer
    expr = 5 * x + 5
End Function
Sub CodeTown()
    Dim i As Integer
    For i = -10 To 10 Step 1
        If expr(i) = 0 Then
            MsgBox "При Y = 0, Х = "+ CStr(i)
            Exit For
        End If
    Next i
End Sub

C помощью команды Exit можно закончить выполнение любого цикла в VBA. Достаточно указать после Exit название используемого цикла. Также им возможно завершить работу любой процедуры или функции.

Цикл For Each в VBA

Блок схема For Each
For Each в VBA основан на переборе всех элементов, указанного типа в массиве, объекте или группе.
Самый популярный вариант его использования — перебор страниц в рабочей книге.

Вывести названия всех листов в рабочей книге

For Each ws In ThisWorkbook.Worksheets
    MsgBox ws.Name
Next ws

И ещё один интересный пример:

Изменить размер шрифта и выравнить по центру текст в label

For Each element In UserForm1.Controls
    If InStr(1, UserForm1.Controls.Item(i%).Name, "Label") > 0 Then
        UserForm1.Controls.Item(i%).TextAlign = fmTextAlignCenter
        UserForm1.Controls.Item(i%).Font.Size = 20
        i% = i% + 1
    End If
Next element

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

Цикл While в VBA

Цикл while VBA
Циклы в VBA, которые используют структуру Do..Loop (это while и until циклы) можно записывать с разным расположением фрагмента условия. Как видите на картинке выше, условие может проверяться после выполнения одной итерации, а может перед запуском цикла.
Самый популярный пример:

Отсортируйте по возрастанию сгенерированный массив методом пузырька

Dim mas(5) As Integer
For i% = 0 To 4
    mas(i%) = Int((10 * Rnd) + 1)
Next i
Dim count As Integer, temp As Integer
count = 1
Do While count > 0
    count = 0
    For i% = 0 To 3
        If mas(i) > mas(i + 1) Then
            temp = mas(i)
            mas(i) = mas(i + 1)
            mas(i + 1) = temp
            count = count + 1
        End If
    Next i%
Loop

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

Цикл Until в VBA

Цикл Until VBA
Как видите, отличия от while крайне несущественные. Цикл Until в VBA можно реализовать с помощью конструкции while NOT (condition). Тем не менее, приведу пример:

Заставить пользователя ввести число

Dim temp As Variant
Do
    temp = InputBox("Введите число")
Loop Until IsNumeric(temp)

Почему заставить? Потому, что если пользователь закроет окно ввода, это его не спасёт, оно будет появляться вновь и вновь пока он не введёт любое число.

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

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.)

Понравилась статья? Поделить с друзьями:
  • Функция find vba excel
  • Функция f4 в excel на ноутбуке
  • Функция exp в excel это
  • Функция excel чтобы считать ячейки
  • Функция excel число дней в году