Excel vba for end for

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

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


For counter = start To end [ Step step ]

    [ statements ]

    [ Exit For ]

    [ statements ]

Next [ counter ]


For счетчик = начало To конец [ Step шаг ]

    [ операторы ]

    [ Exit For ]

    [ операторы ]

Next [ счетчик ]


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

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

Компонент Описание
counter Обязательный атрибут. Числовая переменная, выполняющая роль счетчика, которую еще называют управляющей переменной цикла.
start Обязательный атрибут. Числовое выражение, задающее начальное значение счетчика.
end Обязательный атрибут. Числовое выражение, задающее конечное значение счетчика.
Step* Необязательный атрибут. Оператор, указывающий, что будет задан шаг цикла.
step Необязательный атрибут. Числовое выражение, задающее шаг цикла. Может быть как положительным, так и отрицательным.
statements Необязательный** атрибут. Операторы вашего кода.
Exit For Необязательный атрибут. Оператор выхода из цикла до его окончания.
Next [ counter ] Здесь counter — необязательный атрибут. Это то же самое имя управляющей переменной цикла, которое можно здесь не указывать.

*Если атрибут Step отсутствует, цикл For… Next выполняется с шагом по умолчанию, равному 1.

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

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

Вы можете скопировать примеры циклов в свой модуль VBA, последовательно запускать их на выполнение и смотреть результаты.

Простейший цикл

Заполняем десять первых ячеек первого столбца активного листа Excel цифрами от 1 до 10:

Sub test1()

Dim i As Long

  For i = 1 To 10

    Cells(i, 1) = i

  Next

End Sub

Простейший цикл с шагом

В предыдущий цикл добавлен оператор Step со значением 3, а результаты записываем во второй столбец:

Sub test2()

Dim i As Long

  For i = 1 To 10 Step 3

    Cells(i, 2) = i

  Next

End Sub

Цикл с отрицательными аргументами

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

Sub test3()

Dim i As Long

  For i = 0 To 9 Step 1

    Cells(i + 10, 3) = i + 10

  Next

End Sub

Увеличиваем размер шага до -3 и записываем результаты в четвертый столбец активного листа Excel:

Sub test4()

Dim i As Long

  For i = 0 To 9 Step 3

    Cells(i + 10, 4) = i + 10

  Next

End Sub

Вложенный цикл

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

Sub test5()

Dim i1 As Long, i2 As Long

  For i1 = 1 To 10

‘Пятой ячейке в строке i1 присваиваем 0

    Cells(i1, 5) = 0

      For i2 = 1 To 4

        Cells(i1, 5) = Cells(i1, 5) + Cells(i1, i2)

      Next

  Next

End Sub

Выход из цикла

В шестой столбец активного листа запишем названия десяти животных, конечно же, с помощью цикла For… Next:

Sub test6()

Dim i As Long

  For i = 1 To 10

    Cells(i, 6) = Choose(i, «Медведь», «Слон», «Жираф», «Антилопа», _

    «Крокодил», «Зебра», «Тигр», «Ящерица», «Лев», «Бегемот»)

  Next

End Sub

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

Sub test7()

Dim i As Long

  For i = 1 To 10

    If Cells(i, 6) = «Крокодил» Then

      Cells(i, 7) = «Он съел галоши»

      Exit For

        Else

      Cells(i, 7) = «Здесь был цикл»

    End If

  Next

End Sub


Результат работы циклов For… Next из примеров:

Результат работы циклов For... Next из примеров

Результат работы циклов For… Next

Такие данные на активном листе Excel вы получите, если последовательно запустите на выполнение в редакторе VBA все семь подпрограмм из примеров, демонстрирующих работу циклов For… Next.

Цикл с дробными аргументами

Атрибуты start, end и step могут быть представлены числом, переменной или числовым выражением:

For i = 1 To 20 Step 2

For i = a To b Step c

For i = a 3 To 2b + 1 Step c/2  

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

‘Значения атрибутов до округления

For i = 1.5 To 10.5 Step 2.51

‘Округленные значения атрибутов

For i = 2 To 10 Step 3  

Старайтесь не допускать попадания в тело цикла For… Next неокругленных значений аргументов, чтобы не получить непредсказуемые результаты его выполнения. Если без дробных чисел не обойтись, а необходимо использовать обычное округление, применяйте в коде VBA функцию рабочего листа WorksheetFunction.Round для округления числа перед использованием его в цикле For… Next.


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

Return to VBA Code Examples

In VBA, you can exit a For Loop using the Exit For command.

Exit For

When the execution of the code comes to Exit For, it will exit a For loop and continue with the first line after the loop.

If you want to learn how to exit a Do loop, click on this link: VBA Exit Loop

Exit a For Loop When a Condition is Met

You will see on the example how to exit a For loop when a certain condition is met. We will loop and increment the value of the variable i by 1 in every iteration. When it comes to 5, we want to exit the loop and return a message box. Here is the code:

Dim i As Integer

   For i = 1 To 10     
        If i = 5 Then
            Exit For
        End If
    Next i

MsgBox "The value is " & i

First, we enter the For Loop if the value of i is less than 10:

For i = 1 To 10

Next i

After that we check if the value of i is equal to 5, using the If command. If the value is 5, we exit the For loop and go to the first line after the loop:

If i = 5 Then

    Exit For

End If

If the condition is not met, the following statement increases i by 1 and enters in the For loop again:

Next i

The first line of the code which will be executed after exiting the For loop is the message box with the value of i:

MsgBox "The value is " & i

If you execute this code in the debug mode, you will see that it will go through the loop 5 times. In the 5th iteration, the value of the variable i becomes 5 and the code enters in the If body. Now the body of the For loop is exited. After that, the MsgBox pop-ups with the value of i:

vba exit for

Image 1. Exit For Loop example

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!
vba save as

Learn More!

VBA Break For Loop is also known as the exit for a loop because every process loop has some instructions or criteria to run several times. But, it is very common that some loops get into an infinite loop, thus corrupting the code. In such scenarios, we need a break or exit from the loop to escape certain situations.

Let us say we have instructed the loop to run 10 times. Based on the condition, if the cell value or any other supplied criteria is successful, it has to exit the Excel loop before completing the full loop quota of 10. This article will show you how to exit the loop based on the criteria.

Table of contents
  • Excel VBA Break For Loop
    • How to Break/Exit Loops in VBA?
      • #1 – Break For Next Loop
      • #2 – Break Do Until Loop
    • Recommended Articles

VBA-Break-For-Loop

How to Break/Exit Loops in VBA?

You can download this VBA Break For Loop Excel Template here – VBA Break For Loop Excel Template

#1 – Break For Next Loop

VBA For Next LoopAll programming languages make use of the VBA For Next loop. After the FOR statement, there is a criterion in this loop, and the code loops until the criteria are reached. read more is used to loop over cells and perform specific tasks. For example, look at the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more below.

Code:

Sub Exit_Loop()

 Dim K As Long

 For K = 1 To 10
  Cells(K, 1).Value = K
 Next K

End Sub

It will insert serial numbers from cell A1 to A10.

Break For Loop Example 1

It is the obvious thing with For Next Loop.

We want to break the loop when we find any value in the first ten cells. For this, we have entered some text values in cell A8.

Break For Loop Example 1-1

We want to instruct this in the code, saying, “if the looping cell has a certain value, it has to exit the loop before the pre-determined limit.”

Code:

Sub Exit_Loop()

 Dim K As Long

 For K = 1 To 10
  If Cells(K, 1).Value = "" Then
   Cells(K, 1).Value = K
  Else
   Exit For
  End If
 Next K

End Sub

Look at these lines of code:

If Cells(K, 1).Value = “” Then
Cells(K, 1).Value = K
Else
  Exit For
End If

It says If Cells(K, 1). Value = “looping cell is equal to nothing continue the loop of inserting serial numbers from 1 to 10.

The last part of the loop says:

Else

  Exit For

If the above condition is not TRUE, then the “Exit For” loop.

Now run the code. It will insert serial numbers until the A7 cell.

Break For Loop Example 1-2

The above code immediately exited the loop without saying anything; how do we know it has exited the loop.

To clear this ambiguity, we need to put one simple VBA message boxVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more below.

Code:

Sub Exit_Loop()

 Dim K As Long

 For K = 1 To 10
  If Cells(K, 1).Value = "" Then
   Cells(K, 1).Value = K
  Else
   MsgBox "We got non empty cell, in cell " & 
   Cells(K, 1).Address & vbNewLine & "We are exiting the loop"
   Exit For
  End If
 Next K

End Sub

When looping through the cell, if it finds any non-empty cell, it will display the message saying, “We got non empty cell, in cell A8. We are exiting the loop”.

Exit For Next Loop 1-3

It will also inform the user of the loop’s exit with a cell address. We can check the cell address returned in the message box if we enter any value by mistake.

#2 – Break Do Until Loop

Like how we have exited for Next Loop, we can also exit the “Do Until” loop. For example, look at the below code.

Code:

Sub Exit_DoUntil_Loop()

 Dim K As Long
 K = 1

 Do Until K = 11
   Cells(K, 1).Value = K
   K = K + 1
 Loop

End Sub

This code also performs the task of inserting serial numbers. For example, if we wish to exit the loop when the variable “k” value becomes 6, we need to enter the criteria as IF k = 6 and then exit the loop.

Code:

Sub Exit_DoUntil_Loop()

 Dim K As Long
 K = 1

 Do Until K = 11
  If K < 6 Then
  Cells(K, 1).Value = K
  Else
   Exit Do
 End If
 K = K + 1
Loop

End Sub

It will run the loop until the variable value becomes 6. After that, it will exit the loop. If you wish to show the message to the user, you can add the message box.

Code:

Sub Exit_DoUntil_Loop()

 Dim K As Long
 K = 1

 Do Until K = 11
  If K < 6 Then
  Cells(K, 1).Value = K
  Else
 MsgBox "We are exiting the loop because k value is >5"
  Exit Do
  End If
  K = K + 1
 Loop

End Sub

This will show the message below.

Exit Do Until Loop

Like this, based on the criteria given, we can exit the loop if the criteria are TRUE. Else, we can continue the loop.

Recommended Articles

This article has been a guide to VBA Break For Loop. Here, we learn how to exit/break the VBA loop along with step-by-step examples and a downloadable Excel template. Below are some useful Excel articles related to VBA: –

  • VBA ME Keyword
  • VBA Chr
  • VBA UsedRange
  • VBA Wait

Loops are used in VBA for repeating a set of statements multiple times. Loops form an essential part of any programming language, and VBA is no exception. There are five different types of loops that can be used in VBA. These are as follows:

  • For Loop
  • For Each Loop
  • Do While Loop
  • Do Until Loop
  • Wend Loop (obsolete)

In this post, I will explain all these VBA Loops with examples. But before jumping into the topic, let’s understand what a loop is and why it is used.

What is a loop, and what are its uses?

Loop is an instruction that can continually repeat a set of statements until a particular condition is reached.

Loops can serve the following purposes:

  • It helps in iterating a set of statements.
  • It helps in checking a particular condition multiple times.
  • It can also help in developing custom sleep and wait logic in code.

vba loops

VBA FOR LOOP

For loop is one of the most important and frequently used loop in VBA. For Loop is sometimes also called ‘For Next Loop’.

For Loops allow you to iterate a set of statements for a specified number of times.

Syntax of VBA For Loop

The basic syntax of a VBA For loop or structure of For Loop is as follows:

For loop_ctr = start_num To end_num [step_increment]
'Statements to be executed inside the loop
Next loop_ctr

Here, ‘loop_ctr’ stands for the loop counter. It is the backbone of the ‘For Next Loop,’ and hence it is also called ‘loop timekeeper’. This variable gets incremented after each iteration until the loop ends.

‘start_num’ is the number from which the loop should begin.

‘end_num’ is the number till which the loop should continue.

‘step_increment’ is an optional parameter. It denotes by how much value the ‘loop_ctr’ should be incremented after each iteration. By default, the value of ‘step_increment’ is 1. This means that with each iteration, the ‘loop_ctr’ value is incremented by 1.

How does a VBA For Loop Work?

Let’s say we have a simple For Loop in VBA as shown below:

For loop_ctr = 1 To 100
'Statements to be executed inside the loop
Next loop_ctr
  • When the program control reaches the statement ‘For loop_ctr = 1 To 100’, it reserves a space for the variable ‘loop_ctr’ in the memory and initializes it to 1.
  • After this, it executes the statements inside the For Loop sequentially.
  • Finally, the program control reaches the statement ‘Next loop_ctr’, here it increments the variable ‘loop_ctr’ by 1. And the control again goes to the statement ‘For loop_ctr = 1 To 100’, where it checks if the value of ‘loop_ctr’ has reached 100 or not. If the value is less than 100, then it continues the next iteration; otherwise, the loop stops.

Still not clear with the working of a For Loop? No Worries. Let’s try to understand this with the help of a flow diagram.

VBA For Next Loop Flow Diagram

vba for loop with flow chart

Let’s try to understand the control flow as depicted in the above flow chart:

  1. First of all, the FOR statement is executed. This step allows the ‘loop_ctr’ and ‘step_increment’ values to be initialized.
  2. After this, the condition is evaluated. If the condition is TRUE, all the statements inside the loop ‘Code Block’ are executed. However, If the condition evaluates to FALSE, then the control flow jumps to the next statement outside the For loop.
  3. When the ‘code block’ inside the For Loop executes, the loop starts to get ready for the next iteration and increments the ‘loop_ctr’ value.
  4. Finally, the condition is again evaluated with the incremented ‘loop_ctr,’ and the process repeats itself.

Few Simple Examples of For Loop In VBA

Let’s see some simple examples of For Loop in VBA.

Example 1: Use VBA For Loop to print numbers from 1 to 10 in excel.

In this example, we have a range «A1:A10”, and we have to fill this range with numbers from 1-10.
To accomplish this, we can use the below code:

Sub ForLoopPrintNumbers()
Dim loop_ctr As Integer
For loop_ctr = 1 To 10
ActiveSheet.Range("A1").Offset(loop_ctr - 1, 0).Value = loop_ctr
Next loop_ctr
MsgBox "For Loop Completed!"
End Sub

Explanation:

In the above code, first of all, we have declared the loop counter ‘loop_ctr’ for our For loop. Next, along with the For statement, we have initialized the ‘loop_ctr’ to 1 and set the ‘end_num’ as 10.

Inside the For Loop body, we have written the code to write the loop_ctr value on the excel sheet in the A column. After this, there is a statement that increments the ‘loop_ctr’ for the next iteration.

Note that since we have not specified an explicit ‘step_increment’ value, so every iteration, the ‘loop_ctr’ will be incremented by 1. The For loop in the above code iterates 10 times and populates the cells in the range A1:A10 with numbers from 1-10 serially.

Example 2: Use For Loop in VBA to find the sum of all the numbers between 1 to 10.

In this example, we will loop through all the numbers between 1 to 10 and sum them. Finally, we will be displaying the sum of the numbers from 1 to 10 on the screen.

To do this we can use the following code:

Sub ForLoopSumNumbers()
Dim loop_ctr As Integer
Dim result As Integer
result = 0
For loop_ctr = 1 To 10
result = result + loop_ctr
Next loop_ctr
MsgBox "Sum of numbers from 1-10 is : " & result
End Sub

Explanation:

In the above code, first of all, we have declared the loop counter ‘loop_ctr’ for our For loop. Next, we have declared another integer variable as ‘result’ for storing the sum of numbers from 1 to 10.

After this, along with the For statement, we have initialized the ‘loop_ctr’ to 1 and set the ‘end_num’ as 10.

Inside the For Loop body, we have added the value of ‘loop_ctr’ along with the result. This means that in the first iteration, the result will be: 1, and in the second iteration, it will be : (1+2) = 3. Similarly, in the third iteration, the value will be: (3 + 3) = 6 and so on.

After the For loop body, there is a statement that increments the ‘loop_ctr’ for the next iteration.

Note that since we have not specified an explicit ‘step_increment’ value, hence with every iteration, the ‘loop_ctr’ will be incremented by 1.

The For loop in the above code iterates 10 times and sums all the numbers from 1 to 10, and finally displays the sum of these numbers in msgbox.

Example 3: Use VBA For Loop to print numbers, all even numbers from 1 to 10.

In this example, we will fill all the even numbers between 1 and 10 into cells A1 to A5.

To do this, we can use the below code:

Sub ForLoopToPrintEvenNumbers()
Dim loop_ctr As Integer
Dim cell As Integer
cell = 1

For loop_ctr = 1 To 10
If loop_ctr Mod 2 = 0 Then
ActiveSheet.Range("A1").Offset(cell - 1, 0).Value = loop_ctr
cell = cell + 1
End If
Next loop_ctr

MsgBox "For Loop Completed!"
End Sub

Explanation:

In the above code, first of all, we have declared the loop counter ‘loop_ctr’ for our For loop. After that, we have declared another variable ‘cell’. This variable is initialized with a value of 1.

Next, along with the For statement, we have initialized the ‘loop_ctr’ to 1 and set the ‘end_num’ as 10.

Inside the For Loop body, we have used an IF statement to check if the ‘loop_ctr’ value is even or not.

If the ‘loop_ctr’ value is Even then, we have written a statement to print the value out to the spreadsheet in the A column.

After this, we are incrementing the cell variable by 1. We have used the cell variable in our loop to print the values in the appropriate cell in the A column.

Next, there is a statement that increments the ‘loop_ctr’ for the next iteration.

Note that since we have not specified an explicit ‘step_increment’ value, after every iteration, the ‘loop_ctr’ will be incremented by 1.

The For loop in the above code iterates 10 times and populates the cells in the range A1:A5 with even numbers from 2-10.

Alternate Logic

There is another better way to accomplish the same, let’s see how.

Sub ForLoopToPrintEvenNumbers()
Dim loop_ctr As Integer
Dim cell As Integer
cell = 1

For loop_ctr = 2 To 10 Step 2
ActiveSheet.Range("A1").Offset(cell - 1, 0).Value = loop_ctr
cell = cell + 1
Next loop_ctr

MsgBox "For Loop Completed!"
End Sub

Explanation:

In the above code, we have looped through all the numbers between 2 to 10. Instead of the default ‘step_increment’ of 1, we are using an explicit ‘step_increment’ of 2.

In the first iteration of the for loop, the ‘loop_ctr’ value is 2, which is what gets printed in cell A1. In the second iteration, the ‘loop_ctr’ value becomes 4 (earlier value : 2 + step_increment : 2) and this number gets printed on cell A2.

Similarly, in the third iteration, the ‘loop_ctr’ value is 6 (earlier value: 4 + step_increment: 2) and it gets printed on the cell A3 and so on.

Writing a Nested For Loop

There are times when you might need to use a for loop within another for loop; this is called nesting of for loops.

VBA For loops can be nested within one another to perform complex tasks in excel. Let’s understand a nested loop with an example:

Example 4: Print numbers from 1 to 10 in all the worksheets in an excel spreadsheet using a For Loop.

In this example, we need to print numbers from 1 to 10 in all the worksheets in an excel workbook.

To do this, we can make use of the following code:

Sub ForLoopPrintNumbers()
Dim loop_ctr As Integer
Dim sheet As Integer

For sheet = 1 To Worksheets.Count
For loop_ctr = 1 To 10
Worksheets(sheet).Range("A1").Offset(loop_ctr - 1, 0).Value = loop_ctr
Next loop_ctr
Next sheet

MsgBox "For Loop Completed!"
End Sub

Explanation:

In this example, there are two For Loops, one inside another. The Outer For Loop iterates over the variable ‘sheet’, and the Inner For Loop iterates over ‘loop_ctr’ that determines the cell position.

Inside the body of the Inner For loop, we have a statement that prints the numbers between 1 to 10 in each worksheet (as per the outer loop).

The outer loop iterates over all the available sheets in the spreadsheet, whereas the inner loop iterates over the A1 to A10 for the current sheet. This makes it possible to print numbers from 1 – 10 in all the available worksheets.

Reverse For Loop in VBA

In all our previous examples, we have only seen those For loops in which the loop counter variable gets incremented from a lower value to a higher value (with each iteration).

But this is not necessary, you can also have a For Loop where the loop counter moves from a higher value to a lower value (with each iteration).

Example 5: Use a Reverse For Loop to print numbers from 1 to 10 in descending order.

Sub ReverseForLoop()
Dim loop_ctr As Integer
Dim cell As Integer
cell = 1

For loop_ctr = 10 To 1 Step -1
ActiveSheet.Range("A1").Offset(cell - 1, 0).Value = loop_ctr
cell = cell + 1
Next loop_ctr

MsgBox "For Loop Completed!"
End Sub

Explanation:

In this example, the loop starts with the value of ‘loop_ctr’ as 10. And then, with each iteration, the value of the loop counter is decremented by 1 (since the ‘step_increment’ is -1).

Inside the For Loop body, we print the value of the loop counter variable in the active sheet from A1:A10.

Infinite Loop Using a For Loop

An infinite loop is also sometimes called an Endless Loop. An Infinite Loop is a loop whose ending condition (often due to a logic error by the programmer) never becomes true. The loop iterates an infinite number of times or until halted by programmer/user action.

Although in the case of FOR loop, generally due to the clear start and end conditions, it is not easy to make an endless loop by logical mistake. However, there can be cases where you can by mistake reset the loop counter variable inside the loop, thereby making the loop infinite.

Below is an example of an endless for loop:

'Do not run this code
Sub InfiniteForLoop()
Dim loop_ctr As Integer
Dim cell As Integer

For loop_ctr = 1 To 10
ActiveSheet.Range("A1").Offset(loop_ctr - 1, 0).Value = loop_ctr
loop_ctr = loop_ctr - 1
Next loop_ctr

MsgBox "For Loop Completed!"
End Sub

The statement ‘loop_ctr = loop_ctr – 1’ makes the above VBA loop infinite since it resets the value of the loop_ctr with every iteration, and hence the end condition is never reached.

Tip: It is always good to not make any changes to the loop counter variable value inside the loop body.

How to Break Out or Exit of a For Loop

I believe many of you will wonder, «Why do we need to break a loop during execution»? The answer is simple: Breaking or exiting a loop can sometimes optimize the code and reduce the resource overhead.

To break a For Loop we can use the ‘Exit For’ statement.

Let’s try to see this in action with an example:

Example 6: Use a FOR loop in VBA to find the sum of the first 20 odd numbers between 1 to 100.

In this example, we have to find the first 20 odd numbers from 1 to 100 and then calculate their sum. Below is the code to do this:

Sub SumFirst20OddNumbers()
Dim loop_ctr As Integer
Dim odd_number_counter As Integer
Dim sum As Integer

For loop_ctr = 1 To 100
If (loop_ctr Mod 2 <> 0) Then
sum = sum + loop_ctr
odd_number_counter = odd_number_counter + 1
End If

If (odd_number_counter = 20) Then
Exit For
End If
Next loop_ctr

MsgBox "Sum of top 20 odd numbers is : " & sum
End Sub

Explanation:

In this example, we have three variables – ‘loop_ctr’, ‘odd_number_counter’, and ‘sum’. The variable ‘loop_ctr’ is used as a loop counter, the ‘odd_number_counter’ variable holds the count of odd numbers that have been summed (because we only need to sum the first 20 odd numbers), and the ‘sum’ variable holds the sum of the first 20 odd numbers.

Inside the loop, we iterate all the numbers from 1 to 100, one by one (step_increment is 1 as default), and check if the number is odd. If the number is odd, we sum it and increment the ‘odd_number_counter’ by 1.

After the first IF block, another IF condition checks if the ‘odd_number_counter’ variable value is 20. If the value of ‘odd_number_counter’ is 20, then using the ‘Exit For’ statement, we are exiting out of the loop as there is no point in continuing the loop further.

Few Practical Examples of VBA For Loop

Now let’s have a look at some of the practical examples where For Loop can be used:

Example 7: Highlight alternate rows on a spreadsheet using the VBA For Loop.

In this example, we need to highlight alternate rows in a spreadsheet. To do this we can use the below code:

Sub HighlightAlternateRows()
Dim loop_ctr As Integer
Dim Max As Integer
Dim clm As Integer
Max = ActiveSheet.UsedRange.Rows.Count
clm = ActiveSheet.UsedRange.Columns.Count

For loop_ctr = 1 To Max
If loop_ctr Mod 2 = 0 Then
ActiveSheet.Range(Cells(loop_ctr, 1), Cells(loop_ctr, clm)).Interior.ColorIndex = 28
End If
Next loop_ctr

MsgBox "For Loop Completed!"
End Sub

Explanation:

In the above code, we have started the loop from 1 to the number of rows in our sheet. We are then using the if statement to find the even-numbered rows for highlighting them.

Example 8: Use VBA For Loop Protect all sheets in Workbook.

In this example, we will try to create a VBA macro that loops through all the worksheets in the active workbook and protects all the worksheets.

Below is the code to do this:

Sub ProtectWorksheets()
Dim loop_ctr As Integer
For loop_ctr = 1 To ActiveWorkbook.Worksheets.Count
Worksheets(loop_ctr).Protect
Next loop_ctr
End Sub

Explanation:

In the above code, we are using a VBA for loop and iterating over all the worksheets in the open workbook. Inside the For Loop, we are trying to protect the current instance of the worksheet.

The above code can also be used to unprotect the sheets as well. Just replace the ‘Worksheets(loop_ctr).Protect’ with ‘Worksheets(loop_ctr).UnProtect’.

Example 9: Loop Over an Array of Numbers and Find the Largest and Smallest Numbers from the Array.

In this example, we have an array of numbers, and using a FOR Loop we have to iterate the array and find the smallest and the Largest numbers from the array. Below is the code to do this:

Sub ForLoopWithArrays()
Dim arr() As Variant
arr = Array(10, 12, 8, 19, 21, 5, 16)

Dim min_number As Integer
Dim max_number As Integer

min_number = arr(0)
max_number = arr(0)

Dim loop_ctr As Integer
For loop_ctr = LBound(arr) To UBound(arr)
If arr(loop_ctr) > max_number Then
max_number = arr(loop_ctr)
End If

If arr(loop_ctr) < min_number Then
min_number = arr(loop_ctr)
End If

Next loop_ctr
MsgBox "Largest Number: " & max_number _
& " Smallest Number: " & min_number
End Sub

Explanation:

In the above code, we have an array of numbers declared as ‘arr’ variable. In addition to that, we have two variables, ‘min_number’ and ‘max_number’, that are used for holding the minimum and maximum numbers from the array.

We initialize both the ‘min_number’ and ‘max_number’ variables to the array’s first element. Next, inside the For loop, we loop through all the array elements and check –

If the current number is greater than the ‘max_number’, then set the ‘max_number’ value equal to the current number. The next condition that we check is – If the current number is less than the ‘min_number’, then set the ‘min_number’ value equal to the current number.

Finally, we are showing the largest and the smallest numbers inside the array with the help of a msgbox.

VBA For Each Loop

For each is a more sophisticated type of For Loop. It can be used for iterating a collection of objects.

Here you don’t have to worry about the loop counter, your job is to simply pass a collection of objects, and the loop itself identifies the objects and iterates them.

Syntax of a VBA For Each Loop

The syntax of For Each Loop resembles closely to For Loop. Below is the syntax:

For Each item In collection_of_items
'Statements to be executed inside the loop
Next item

Here, ‘collection_of_items’ refers to a group of objects that you need to iterate. If you supply a single object to this parameter, it throws a «run-time error 438».

‘item’ specifies the objects inside the ‘collection_of_items’. At any particular instant inside the loop, ‘item’ contains a single object from the ‘collection_of_items’.

How a For Each Loop Works

Let’s say we have a For Each Loop as:

For Each cl In ActiveSheet.Range("A1:A10")
'Statements to be executed inside the loop
Next cl
  • When the program control reaches the statement ‘For Each cl In ActiveSheet.Range(«A1:A10»)’ it evaluates the object collection and then initializes the variable ‘cl’ with the first object in the collection, i.e., cell $A$1.
  • After this, it executes the statements inside the loop.
  • Next, it fetches the second object from the collection and dumps it in the variable ‘cl’. And the process continues till it has fetched all objects from the collection.

Flow Diagram of a For Each Loop In VBA

VBA_ForEach Loop FlowChart

Let’s try to understand the control flow as depicted in the above flow chart:

  1. First of all, the FOR EACH statement is executed and checks if there are any elements in the collection.
  2. If there are any elements present in the collection, the ‘item’ variable is initialized to the first element of the collection, and the statements inside the loop ‘Code Block’ is executed. However, If the condition evaluates to FALSE, then the control flow jumps to the next statement outside the For Each loop.
  3. When the ‘code block’ inside the For Each Loop executes, the loop starts to get ready for the next iteration. The ‘item’ variable is re-initialized to the next element in the collection, and the loop continues.

Few Simple Examples of VBA For Each Loop

Now let’s move to some simple examples of For Each loop.

Example 1 – Use VBA For Each Loop to display the names of all the Active Worksheets.

In this example, we will use a For Each loop to iterate through all the worksheets in the ActiveWorkbook and display the names of all the sheets using a msg box.

Sub ForEachDisplaySheetNames()
Dim sheetNames As String
For Each sht In ActiveWorkbook.Sheets
sheetNames = sheetNames & vbNewLine & sht.Name
Next sht

MsgBox "The Sheet names are : " & vbNewLine & sheetNames
End Sub

Explanation:

In this example, the For Each loop takes the collection of sheets from ‘ActiveWorkbook.Sheets’ it then iterates the sheets one by one and initializes the ‘sht’ variable with the current sheet instance.

Inside the For Each block, the sheet name for each worksheet is appended to a string, and finally, outside the loop, all the sheet names are displayed using a message box.

Example 2: Use VBA For Each Loop to Sum all the Elements of an Array.

In this example, with the help of a VBA For Each loop, we will be iterating an array of numbers and find the sum of all of its elements. Below is the code to do this:

Sub ForEachSumArrayElements()
Dim arr As Variant
Dim sum As Integer
arr = Array(1, 10, 15, 17, 19, 21, 23, 27)

For Each element In arr
sum = sum + element
Next element

MsgBox "The Sum is : " & sum
End Sub

Explanation:

In the above code, we have declared two variables, ‘arr’ and ‘sum’. The ‘arr’ variable is used for storing the array of numbers, and the ‘sum’ variable represents the sum of the array elements.

Inside the For Each loop, we are iterating the array elements one by one, summing them up, and storing the total in the ‘sum’ variable.

Finally, outside the For Each loop, we show the sum of the array elements using a message box.

Example 3: Use VBA For Each Loop to display the names of all the Open Workbooks.

In this example, using a For Each loop, we will loop through all the open workbooks and display their name using a message box.

Below is the code to do this:

Sub ForEachDisplayWorkbookNames()
Dim workBookNames As String

For Each wrkbook In Workbooks
workBookNames = workBookNames & vbNewLine & wrkbook.Name
Next wrkbook

MsgBox "The Workbook names are : " & vbNewLine & workBookNames
End Sub

Explanation:

In this example, the For Each loop takes the collection of workbooks, then iterates the workbooks one by one and initializes the ‘wrkbook’ variable with the current workbook instance.

Inside the For Each block, the workbook name for each workbook is appended to a string, and finally, outside the loop, all the workbook names are displayed using a message box.

Nested VBA For Each Loop

Two For Each loops can be nested within one another to perform complex tasks. Let’s understand For Each nested loop with an example:

Example 4: Display the names of all open workbooks along with their corresponding worksheets.

In this example, we will be iterating through all the open workbooks and then iterate through each workbook’s worksheets and finally display them using a message box.

Below is the code to do this:

Sub ForEachLoopNesting()
Dim result As String
For Each wrkbook In Workbooks
For Each sht In wrkbook.Sheets
result = result & vbNewLine & " Workbook : " & wrkbook.Name & " Worksheet : " & sht.Name
Next sht
Next wrkbook

MsgBox result
End Sub

Explanation:

In the above code, we have used two For Each loops, one inside another. The outer For Each loop iterates through the workbooks, and the inner For Each loop iterates through the worksheets.

Inside the inner For Each block, a statement concatenates the names of the workbooks and the worksheets and stores them in a variable called ‘result’.

With each iteration, the ‘result’ variable’s new value is appended to the existing value. Finally, the value of the ‘result’ variable is displayed inside a msgbox.

How to Break Out or Exit of a For Each Loop

To break out of a For Each loop, we can use the ‘Exit For’ statement. So, ‘Exit For’ statement can break both a For loop as well as a For Each loop.

Let’s see this with an example:

Example 5: Use VBA For Each Loop to display the names of the first 3 sheets in the active workbook.

In this example, we will loop through the worksheets inside the active workbook and only display the first 3 worksheet names. Below is the code to do this:

Sub ForEachDisplayFirstThreeSheetNames()
Dim sheetNames As String
Dim sheetCounter As Integer

For Each sht In ActiveWorkbook.Sheets
sheetNames = sheetNames & vbNewLine & sht.Name
sheetCounter = sheetCounter + 1

If sheetCounter >= 3 Then
Exit For
End If
Next sht

MsgBox "The Sheet names are : " & vbNewLine & sheetNames
End Sub

Explanation:

In the above code, we have a For Each loop that iterates over the worksheets inside the active workbook. Inside the loop, we are appending and storing the sheet names within the ‘sheetNames’ variable. Also, we have a ‘sheetCounter’ variable that gets incremented on each iteration.

After that, inside the loop, we also check if the value of the ‘sheetCounter’ variable has reached 3 (because we only want to display 3 sheet names).

If the ‘sheetCounter’ variable’s value has reached 3, we exit the loop using the ‘Exit For’ statement. Finally, we are displaying the value of the ‘sheetNames’ variable using a msgbox.

VBA Do While Loop

VBA Do While is another type of loop that repeatedly executes a set of statements while a condition continues to be True. The loop ends when the condition becomes false.

Syntax of Do While Loop In VBA

Do while loop has two syntaxes in VBA, these are as follows:

Syntax 1:

Do While condition
'Statements to be executed inside the loop
Loop

Or

Syntax 2:

Do
'Statements to be executed inside the loop
Loop While condition

In both the syntaxes, ‘condition’ is used as the loop backbone. On each iteration ‘While’ statement checks if the ‘condition’ evaluates to True or False. If the ‘condition’ is True, then the loop continues; otherwise, the loop terminates.

Before everything else, let’s try to understand the difference between these two syntaxes.

Difference Between the two Do While Syntaxes

As we can see in the first, do-while loop syntax, the ‘condition’ is checked as the first statement. This means if the condition is false, the do-while loop in syntax 1 will not perform any iterations.

Whereas in the second syntax, the ‘condition’ is checked as the last statement inside the loop. This means that even if the condition is false, the do-while loop in syntax 2 will perform at least 1 iteration. Only after that, the condition will be evaluated, and the next iteration will not happen.

So, syntax 2 guarantees to have at least 1 iteration irrespective of the condition being true or false.

Now, let’s try to understand how a do-while loop works.

How Does a Do While Loop Work

Syntax 1 –

Let’s say we have a Do While loop as follows:

Dim loop_ctr as Integer
loop_ctr = 1
Do While loop_ctr < 10
'Statements to be executed inside the loop
loop_ctr = loop_ctr + 1
Loop
  • In the first two statements, the variable ‘loop_ctr’ is declared and initialized as 1.
  • When the program control reaches the statement «Do While loop_ctr < 10», it checks if the value of the ‘loop_ctr’ is less than 10.
  • If the ‘loop_ctr’ value is less than 10, the statements inside the body of the loop get executed sequentially, and finally, the ‘loop_ctr’ is incremented by 1.
  • After this, the control again moves to the loop «Do While loop_ctr < 10», and the loop continues till the value of ‘loop_ctr’ becomes equal to 10.
  • When the value of ‘loop_ctr’ becomes equal to 10, then the do while condition fails, and the control moves to the next statement after the do-while loop.

Syntax 2 –

Let’s say we have a Do While loop as follows:

Dim loop_ctr as Integer
loop_ctr = 1
Do
'Statements to be executed inside the loop</em>
loop_ctr = loop_ctr + 1
Loop While loop_ctr < 10
  • In the first two statements, the variable ‘loop_ctr’ is declared and initialized as 1.
  • When the program control reaches the «Do» statement, as there are no checks (like syntax 1), it just comes inside the loop and starts executing the statements inside the loop one by one and increments the ‘loop_ctr’ by 1.
  • After executing the statements inside the loop body, it checks if the ‘loop_ctr’ is less than 10. If the ‘loop_ctr’ value is less than 10, another iteration starts.
  • If the value of ‘loop_ctr’ becomes equal to 10, then the do while condition fails, and the control moves to the next statement after the do-while loop.

Note: In the second syntax, the Do-While Loop always iterates at-least-once since the condition to be checked is placed at the end of the loop.

Flow Diagram of a Do While Loop In VBA:

VBA Do While Loop With Flow Chart

Let’s try to understand the control flow as depicted in the above flow chart:

Syntax 1 –

  1. In this Do-While syntax, the loop condition is checked along with the Do statement.
  2. If the condition is true, then the ‘code block’ inside the do-while loop is executed, and the next iteration begins. Each iteration before beginning checks the loop condition, and the ‘code block’ inside the do-while loop is only executed when the condition evaluates to true.
  3. When the loop condition becomes false, then no more loop iterations occur, and the control flow jumps to the next statement outside the Do While loop.

Syntax 2 –

  1. In this Do-While syntax, the loop condition is not checked along with the Do statement.
  2. Since for the first iteration, no condition is checked. Hence the code block inside the do-while body gets executed.
  3. After the first iteration, each subsequent iteration, before beginning, checks the loop condition, and the ‘code block’ inside the do-while loop is only executed when the condition evaluates to true.
  4. When the loop condition becomes false, then no more loop iterations occur, and the control flow jumps to the next statement outside the Do While loop.

Few Simple Examples of Do While Loop In VBA

Example 1: Use VBA Do While Loop to print numbers from 1 to 10 in excel.

In this example, we have a range «A1:A10,» and we have to fill this range with numbers from 1-10. To do this we can use the below code:

Sub DoWhileLoopPrintNumbers()
Dim loop_ctr As Integer
loop_ctr = 1

Do While loop_ctr <= 10
ActiveSheet.Range("A1").Offset(loop_ctr - 1, 0).Value = loop_ctr
loop_ctr = loop_ctr + 1
Loop

MsgBox ("Loop Ends")
End Sub

Explanation:

In the above code, we have declared and initialized the ‘loop_ctr’ variable for our Do While loop. Next, along with the Do while statement, we have a condition to run the loop till the ‘loop_ctr’ value is less than or equal to 10.

Inside the Do While Loop body, we have written the code to write the ‘loop_ctr’ value on the excel sheet in the A column.

After this, there is a statement that increments the ‘loop_ctr’ for the next iteration.

Example 2: Use Do While Loop in VBA to find the sum of all the numbers between 1 to 20.

In this example, we will loop through all the numbers between 1 to 20 and sum them. Finally, we will be displaying the sum of the numbers from 1 to 20 on the screen.

To do this we can use the following code:

Sub WhileLoopSumNumbers()
Dim loop_ctr As Integer
Dim result As Integer
loop_ctr = 1
result = 0

Do While loop_ctr <= 20
result = result + loop_ctr
loop_ctr = loop_ctr + 1
Loop

MsgBox "Sum of numbers from 1-20 is : " & result
End Sub

Explanation:

In the above code, we have declared the loop counter ‘loop_ctr’ for our Do While loop. Next, we have declared another integer variable as ‘result’ for storing the sum of numbers from 1 to 20.

After this, along with the Do while statement, we have a condition to run the loop till the ‘loop_ctr’ value is less than or equal to 20.

Inside the Do While Loop body, we have added the value of ‘loop_ctr’ along with the result. This means that in the first iteration, the result’s value will be: 1, and in the second iteration, it will be : (1+2) = 3. Similarly, in the third iteration, the value will be: (3 + 3) = 6 and so on.

After this, there is a statement that increments the ‘loop_ctr’ for the next iteration.

The Do While loop in the above code iterates 20 times, sums all the numbers from 1 to 20, and finally displays the sum of these numbers in msgbox.

Example 3: Show the unique behavior of Do While Loop (In Syntax 2) to execute at-least-once even if the condition to be checked is False.

Sub DoWhileLoopTest()
Dim loop_ctr As Integer
loop_ctr = 100

Do
MsgBox "Loop Counter : " & loop_ctr
loop_ctr = loop_ctr + 1
Loop While loop_ctr <= 10

End Sub

Explanation:

In the above example, we have initialized the ‘loop_ctr’ as 100 and inside the loop condition we are checking ‘loop_ctr < 10’. This means the loop is only designed to iterate when the value of ‘loop_ctr’ is less than 10. But you will notice that despite the condition this do-while loop executes once.

The reason for this is: because according to syntax 2 of the Do While loop, there is no way to check conditions at the beginning of the loop. You can only check conditions at the end of the loop.

Note: We can fix this issue by simply using the Do While loop in Syntax 1 as shown:

Sub DoWhileLoopTest()
Dim loop_ctr As Integer
loop_ctr = 100

Do While loop_ctr <= 10
MsgBox "Loop Counter : " & loop_ctr
loop_ctr = loop_ctr + 1
Loop

End Sub

Writing a Nested Do While Loop

Similar to other loops, nesting is very much possible in Do While Loops. Let’s understand nested Do While loops this with an example.

Example 4: Print numbers from 1 to 10 in all the worksheets in an excel spreadsheet using a Do While Loop.

In this example, we need to print numbers from 1 to 10 in all the worksheets in an excel workbook using a do-while loop. To do this, we can make use of the following code:

Sub NestedDoWhileLoop()
Dim loop_ctr As Integer
Dim sheet As Integer
sheet = 1

Do While sheet <= Worksheets.Count
loop_ctr = 1
Do While loop_ctr <= 10
Worksheets(sheet).Range("A1").Offset(loop_ctr - 1, 0).Value = loop_ctr
loop_ctr = loop_ctr + 1
Loop
sheet = sheet + 1
Loop

MsgBox "Nested While Loop Completed!"
End Sub

Explanation:

In this example, there are two Do While Loops, one inside another. The Outer Do While Loop iterates over the variable ‘sheet’ and iterates till the value of the ‘sheet’ variable is less than or equal to ‘Worksheets.Count’ (i.e., the total count of worksheets in a workbook).

Inner Do While Loop iterates over the variable ‘loop_ctr’ and iterates till the value of ‘loop_ctr’ is less than or equal to 10. This helps us to print the numbers in a sequence.

Inside the body of the Inner Do While loop, we have a statement that prints the numbers between 1 to 10 in each worksheet (as per the outer loop).

The outer loop iterates over all the available worksheets sheets in the spreadsheet, whereas the inner loop iterates over the numbers from 1 to 10 for the current sheet.

This makes it possible to print numbers from 1 – 10 in all the available worksheets.

Infinite Loop Using a Do While Loop

Unlike a For Loop, a Do While Loop does not have a clear ‘start’, ‘end’ or ‘step_increments’, so it is very easy to make logical errors resulting in an infinite or an endless loop. Below is an example of a Do While endless loop:

'Do not run this code
Sub InfiniteDoWhileLoop()
Dim loop_ctr As Integer
loop_ctr = 1

Do While loop_ctr <= 10
ActiveSheet.Range("A1").Offset(loop_ctr - 1, 0).Value = loop_ctr
Loop

MsgBox ("Loop Ends")
End Sub

In the above code, we have simply missed the line to increment the loop counter i.e. ‘loop_ctr = loop_ctr + 1’ and this has made the loop infinite because the value of ‘loop_ctr’ will always be 1 (since it is never incremented) and hence the loop condition ‘While loop_ctr <= 10’ will always evaluate to true.

Tip: It is always a good idea to use a For Each or For Next loop over a Do While or Do Until loop (whenever possible).

How to Break Out or Exit of a Do While Loop

To break out of a Do While loop, we can use the ‘Exit Do’ statement. As soon as the VBA engine executes the ‘Exit Do’ statement, it exits the loop and takes the control to the next statement after the Do while loop.

Let’s see this with an example:

Example 5: Use a Do While loop in VBA to find the sum of the first 15 odd numbers between 1 to 100.

In this example, we have to find the first 15 odd numbers from 1 to 100 and then calculate their sum. Below is the code to do this:

Sub SumFirst15OddNumbers()
Dim loop_ctr As Integer
Dim odd_number_counter As Integer
Dim sum As Integer

loop_ctr = 1

Do While loop_ctr <= 100
If (loop_ctr Mod 2 <> 0) Then
sum = sum + loop_ctr
odd_number_counter = odd_number_counter + 1
End If

If (odd_number_counter = 15) Then
Exit Do
End If

loop_ctr = loop_ctr + 1
Loop

MsgBox "Sum of top 15 odd numbers is : " & sum
End Sub

Explanation:

In this example, we have three variables – ‘loop_ctr’, ‘odd_number_counter’, and ‘sum’. ‘loop_ctr’ is the loop counter variable, ‘odd_number_counter’ variable holds the count of odd numbers that have been summed and the ‘sum’ variable holds the sum of the first 15 odd numbers.

Inside the Do While loop, we loop through all the numbers from 1 to 100, one by one, and check if the number is odd. If the number is odd, we sum it and increment the ‘odd_number_counter’ by 1.

After the first IF block, another IF condition checks if the ‘odd_number_counter’ variable value is 15. If the value of ‘odd_number_counter’ is 15, then using the ‘Exit Do’ statement, we are breaking the loop as there is no point in continuing the loop further.

Finally, we are displaying the value of the ‘sum’ variable using a msgbox.

VBA Do Until Loop

Do Until loop is very similar to Do While loop; the only difference between them is that –

  • A ‘do-while’ loop iterates as long as a certain condition is true.
  • On the other hand, a ‘do-until’ loop iterates until a condition is no longer true.

Let’s try to understand this difference in simple terms:

For Instance: If we want to write a Do Loop that iterates from 1 to 10, with while keyword, the condition would be ‘Do While loop_ctr <= 10’ and with until keyword, the same condition can be written as ‘Do Until loop_ctr > 10’.

Which means:

  • Until – repeat Until the count is greater than ten
  • While – repeat While the count is less than or equal to ten

With these examples, you can clearly see – using Until and While is just the opposite way of writing the same condition.

Now, let’s have a look at the syntax of Do Until Loop.

Syntax of Do Until Loop In VBA

Similar to Do While loop, Do Until also has two syntaxes:

Syntax 1 –

Do Until condition
'Statements to be executed inside the loop
Loop

Or

Syntax 2 –

Do
'Statements to be executed inside the loop
Loop Until condition

Here, ‘condition’ is used as the loop backbone, the same as in the case of Do While Loop. On each iteration, Until statement checks, if the ‘condition’ evaluates to True or False. If the ‘condition’ is False, then the loop continues. Otherwise, the loop ends.

Now, let’s try to understand the difference between these two syntaxes.

Difference Between the two Do Until Syntaxes

As we can see in the first do until loop syntax, the ‘condition’ is checked as the first statement. This means if the condition is true, the do-until loop in syntax 1 will not perform any iterations.

Whereas in the second syntax, the ‘condition’ is checked as the last statement inside the loop. This means that even if the condition is true, the do-until loop in syntax 2 will perform at least 1 iteration. Only after that, the condition will be evaluated, and the next iteration will not happen.

So, syntax 2 guarantees to have at least 1 iteration irrespective of the condition being true or false.

How a Do Until Loop Works

Syntax 1 –

Let’s say we have a Do Until loop as follows:

Dim loop_ctr As Integer
loop_ctr = 1
Do Until loop_ctr > 10
'Statements to be executed inside the loop
loop_ctr = loop_ctr + 1
Loop
  • In the first two statements, a variable ‘loop_ctr’ is declared and initialized as 1.
  • When the program control reaches the statement «Do Until loop_ctr > 10», it checks if the value of the ‘loop_ctr’ is greater than 10.
  • If the ‘loop_ctr’ value is less than or equal to 10, the statements inside the body of the loop get executed sequentially, and finally, the ‘loop_ctr’ is incremented by 1.
  • After this, the control again moves to check the condition «Do Until loop_ctr > 10», and the loop continues till the value of ‘loop_ctr’ is less than or equal to 10.

Syntax 2 –

Dim loop_ctr As Integer
loop_ctr = 1
Do
'Statements to be executed inside the loop
loop_ctr = loop_ctr + 1
Loop Until loop_ctr > 10
  • In the first two statements, a variable ‘loop_ctr’ is declared and initialized as 1.
  • When the program control reaches the statement Do, it simply moves to the next statement as the Do statement doesn’t force the program to check any condition.
  • After this, in the following statement, a variable ‘loop_ctr’ is incremented by 1.
  • Next, ‘Loop Until loop_ctr > 10’ statement checks if the value of ‘loop_ctr’ is greater than 10 or not. If it is less than or equal to 10, then the program control again jumps to the Do statement, but if the value of ‘loop_ctr’ is greater than 10, it terminates the loop and the program control moves to the next statement.

Note: Syntax 2 of Do Until Loop always iterates at-least-once since the condition that is to be checked is placed at the end of the loop.

Flow Diagram of a Do Until Loop In VBA

Do Unitl Loop VBA Flowchart

Let’s try to understand the control flow as depicted in the above flow chart:

Syntax 1 –

  1. In this Do-Until syntax, the loop condition is checked along with the Do statement.
  2. If the condition is false, then the ‘code block’ inside the do-until loop is executed, and the next iteration begins. Each iteration before beginning checks the loop condition, and the ‘code block’ inside the do-until loop is only executed when the condition evaluates to false.
  3. When the loop condition becomes true, then no more loop iterations occur, and the control flow jumps to the next statement outside the Do Until loop.

Syntax 2 –

  1. In this Do-Until syntax, the loop condition is not checked along with the Do statement.
  2. Since for the first iteration, no condition is checked. Hence the code block inside the do-until body gets executed.
  3. After the first iteration, each subsequent iteration, before beginning, checks the loop condition, and the ‘code block’ inside the do-until loop is only executed when the condition evaluates to false.
  4. When the loop condition becomes true, then no more loop iterations occur, and the control flow jumps to the next statement outside the Do Until loop.

Few Simple Examples of Do Until Loop In VBA

Example 1: Print numbers from 1 to 10 in excel using a VBA Do Until Loop.

In this example, we have a range «A1:A10,» and we have to fill this range with numbers from 1-10. To do this we can use the below code:

Sub DoUntilLoopPrintNumbers()
Dim loop_ctr As Integer
loop_ctr = 1

Do Until loop_ctr < 10
ActiveSheet.Range("A1").Offset(loop_ctr - 1, 0).Value = loop_ctr
loop_ctr = loop_ctr + 1
Loop

MsgBox ("Loop Ends")
End Sub

Explanation:

In the above code, first of all, we have declared and initialized the ‘loop_ctr’ variable for our Do Until loop. Next, along with the Do until statement, we have a condition to run the loop till ‘loop_ctr’ value is greater than 10.

Inside the Do Until Loop body, we have written the code to write the ‘loop_ctr’ value on the excel sheet in the A column.

After this, there is a statement that increments the ‘loop_ctr’ for the next iteration. As soon as the value of the ‘loop_ctr’ variable becomes greater than 10, the loop ends.

Example 2: Use Do Until Loop in VBA to find the sum of all the numbers between 1 to 20.

In this example, using a do until loop, we will iterate all the numbers between 1 to 20 and sum them. Finally, we will be displaying the sum of the numbers from 1 to 20 on the screen. To do this we can use the following code:

Sub DoUntilLoopSumNumbers()
Dim loop_ctr As Integer
Dim result As Integer
loop_ctr = 1
result = 0

Do Until loop_ctr > 20
result = result + loop_ctr
loop_ctr = loop_ctr + 1
Loop

MsgBox "Sum of numbers from 1-20 is : " & result
End Sub

Explanation:

In the above code, we have declared the loop counter ‘loop_ctr’ for our Do Until loop. Next, we have declared another integer variable as ‘result’ for storing the sum of numbers from 1 to 20.

After this, along with the Do Until statement, we have a condition to run the loop until the ‘loop_ctr’ becomes greater than 20.

Inside the Do Until Loop body, we have added the value of ‘loop_ctr’ along with the result. This means in the first iteration, the value of the result will be: 1, and in the second iteration, it will be : (1+2) = 3; similarly, in the third iteration, the value will be: (3 + 3) = 6 and so on.

After this, there is a statement that increments the ‘loop_ctr’ for the next iteration.

The Do Until loop in the above code iterates 20 times and sums all the numbers from 1 to 20, and finally displays the sum of these numbers in msgbox.

Example 3: Show the unique behavior of Do Until Loop (In Syntax 2) to execute at-least-once even if the condition to be checked is True.

Sub DoUntilLoopTest()
Dim loop_ctr As Integer
loop_ctr = 100

Do
MsgBox "Loop Counter : " & loop_ctr
loop_ctr = loop_ctr + 1
Loop Until loop_ctr > 10
End Sub

Explanation:

In the above example, we have initialized the ‘loop_ctr’ as 100 and inside the loop condition we are checking ‘loop_ctr > 10’. This means the loop is only designed to iterate when the value of ‘loop_ctr’ is less than 10. But you will notice that despite the condition this do-until loop executes once.

The reason for this is: because according to syntax 2 of the Do Until loop, there is no way to check conditions at the beginning of the loop. The condition can only be checked at the end of the loop.

Note: We can fix this issue by simply using the Do Until loop in Syntax 1 as shown:

Sub DoUntilLoopTest()
Dim loop_ctr As Integer
loop_ctr = 100

Do Until loop_ctr > 10
MsgBox "Loop Counter : " & loop_ctr
loop_ctr = loop_ctr + 1
Loop
End Sub

Writing a Nested Do Until Loop

Similar to other loops nesting is very much possible in Do Until Loop. Let’s see how to write a nested Do Until loop:

Example 4: Print numbers from 1 to 5 in all the worksheets in an excel spreadsheet using a Do Until Loop.

In this example, we need to print numbers from 1 to 5 in all the worksheets in an excel workbook using a do until loop. To do this, we can make use of the following code:

Sub NestedDoUntilLoop()
Dim loop_ctr As Integer
Dim sheet As Integer
sheet = 1

Do Until sheet > Worksheets.Count
loop_ctr = 1
Do Until loop_ctr > 5
Worksheets(sheet).Range("A1").Offset(loop_ctr - 1, 0).Value = loop_ctr
loop_ctr = loop_ctr + 1
Loop
sheet = sheet + 1
Loop

MsgBox "Nested Do Until Loop Completed!"
End Sub

Explanation:

In this example, there are two Do Until Loops, one inside another. The Outer Do Until Loop iterates over the variable ‘sheet’ and iterates until the value of the ‘sheet’ variable becomes greater than ‘Worksheets.Count’ (i.e., the total count of worksheets in a workbook).

Inner Do Until Loop iterates over the variable ‘loop_ctr’ and iterates until the value of ‘loop_ctr’ becomes greater than 5. This helps us to print the numbers in a sequence.

Inside the body of the Inner Do Until loop, we have a statement that prints the numbers between 1 to 5 in each worksheet (as per the outer loop).

The outer loop iterates over all the available worksheets in the spreadsheet, whereas the inner loop iterates over the numbers from 1 to 5 for the current sheet.

This makes it possible to print numbers from 1 – 5 in all the available worksheets.

Infinite Loop Using a Do Until Loop

Syntactically, Do Until Loop is very different from a For Loop since it does not provide a clear ‘start’, ‘end’ or ‘step_increments’, so it is very easy to make logical errors resulting in an infinite or an endless loop.

Below is an example of a Do Until endless loop:

'Do not run this code
Sub InfiniteDoUntilLoop()
Dim loop_ctr As Integer
loop_ctr = 1

Do Until loop_ctr > 10
ActiveSheet.Range("A1").Offset(loop_ctr - 1, 0).Value = loop_ctr
Loop

MsgBox ("Loop Ends")
End Sub

In the above code, we have simply missed the line to increment the loop counter i.e. ‘loop_ctr = loop_ctr + 1’ and this has made the loop infinite because the value of ‘loop_ctr’ will always be 1 (since it is never incremented) and hence the loop condition ‘Until loop_ctr > 10’ will always evaluate to false.

Tip: It is always a good idea to use a For Each or For Next loop over a Do While or Do Until loop (whenever possible).

How to Break Out or Exit of a Do Until Loop

Similar to a Do While Loop, a Do Until loop can also be exited using an ‘Exit Do’ statement. As soon as the VBA engine executes the ‘Exit Do’ statement, it exits the loop and takes control to the next statement after the Do Until loop.

Let’s see this with an example:

Example 5: Use a Do Until loop in VBA to find the sum of the first 20 even numbers between 1 to 100.

In this example, we must find the first 20 even numbers from 1 to 100 and then calculate their sum.

Below is the code to do this:

Sub SumFirst20EvenNumbers()
Dim loop_ctr As Integer
Dim even_number_counter As Integer
Dim sum As Integer

loop_ctr = 1

Do Until loop_ctr < 100
If (loop_ctr Mod 2 = 0) Then
sum = sum + loop_ctr
even_number_counter = even_number_counter + 1
End If

If (even_number_counter = 20) Then
Exit Do
End If

loop_ctr = loop_ctr + 1
Loop

MsgBox "Sum of top 20 even numbers is : " & sum
End Sub

Explanation:

In this example, we have three variables – ‘loop_ctr’, ‘even_number_counter’, and ‘sum’. ‘loop_ctr’ is the loop counter variable, ‘even_number_counter’ variable holds the count of even numbers that have been summed (because we only need to sum the first 20 even numbers) and ‘sum’ variable holds the sum of the first 20 even numbers.

Inside the Do Until loop, we loop through all the numbers from 1 to 100, one by one, and check if the number is even. If the number is even, we sum it and increment the ‘even_number_counter’ by 1.

After the first IF block, another IF condition checks if the ‘even_number_counter’ variable value is 20. If the value of ‘even_number_counter’ is 20, then using the ‘Exit Do’ statement, we break the loop as there is no point in running the loop further.

While Wend Loop In VBA (Obsolete)

While Wend loop was added in VBA just to make it backward compatible, Microsoft recommends using Do While Loop in place of While Wend Loop.

While Wend Loop is not as structured and flexible like a Do While Loop, it also doesn’t support the idea of prematurely exiting out of the loop.

Tip: If you are learning loops in VBA, then you can skip this topic. However, if you are dealing with a legacy code with While Wend statements, I would recommend you change them and start using the Do while loops instead.

Syntax of While Wend Loops

The syntax of While Wend Loop is as follows:

While condition
'Statements to be executed inside the loop
Wend

‘condition’ is used as the loop backbone. On each iteration, the While statement checks if the ‘condition’ evaluates to True or False. If the ‘condition’ is True, then the loop continues; otherwise, the loop terminates.

Example: Write a While Wend loop to print numbers from 1 to 10.

To do this, we can write the below code:

Sub WhileWendExample()
Dim loop_ctr As Integer
loop_ctr = 1

While loop_ctr <= 10
ActiveSheet.Range("A1").Offset(loop_ctr - 1, 0).Value = loop_ctr
loop_ctr = loop_ctr + 1
Wend

MsgBox "Loop Ends!"
End Sub

Explanation:

In the above code, first of all, we are declaring and initializing a loop counter variable ‘loop_ctr’ as 1. Next, there is a While statement along with the condition ‘While loop_ctr <= 10’.

This means that we need to iterate until the value of the ‘loop_ctr’ variable is less than or equal to 10. After this, we are printing the value of ‘loop_ctr’ in the active worksheet and then incrementing the loop counter. When the Wend statement is encountered, the next iteration starts.

The loop in the above example iterates 10 times, and after that, the value of ‘loop_ctr’ becomes 11, and hence the loop condition becomes false, and the control moves to the statement after the while when loop.

Finally, a message’ Loop Ends!’ is presented on the screen to notify the user that the loop has ended.

How To Write VBA Code In Excel

VBA code can be added to a spreadsheet using the Visual Basic Editor. To open the Visual Basic Editor in Excel, follow the below steps:

  • If you are on Windows, press the keys (ALT + F11). If you are on MAC, press the keys (Opt + F11). This will open the Visual Basic Editor.

open_vba_editor

  • After the Visual Basic Editor is opened. Go to «Insert» and click the «Module» option as shown in the image. This will insert a module object for your workbook.

Run vba code in excel

  • Now you can copy-paste the above codes in the module and run them using the execute button as shown.

Debugging Tips

  • Use the F5 key to run the code.
  • Use the F9 key to insert or remove a breakpoint.
  • Use the F8 key to ‘step-into’ or run the code line by line. It can be used to debug the code and execute it line by line.

So, this was all about VBA Loops. Do let us know in case you have any queries related to the topic.

Loops in VBA

Loops are an essential part of any programming language because they help with the repeated running of any code snippet. Just like any other language, VBA offers the following loops to enable efficient programming:

  1. Do until
  2. Do while
  3. For
  4. Foreach

In this article we will dive dep into the “for” loop which iterates only for “x” number of times where “x” is a known value before the loop’s runtime.

“X” can also be a predictable number at runtime, for example when you determine the Lbound and Ubound values of arrays.

The For Loop in VBA

In VBA, “for loop” is easy to use. It follows a simple and understandable syntax.

Syntax:

For <counter> = <start> to <end> [ <step value> ]

[ <code block to execute> ]

Next [ <counter> ]

where

<counter> is the iterator variable which keeps incrementing by the <step value> after every iteration. 

<step value> is optional. If this value is not provided, the default incremental value is “1.”

<Code block to execute> is also optional. It is the snippet of code to be executed during every iteration.

The “Next” statement marks the end of the “for” loop. It indicates to move to the next iteration of this loop with the incremented counter value.

Simple Examples of a For Loop

Print a Mathematical Table for a Number

Sub forloop_demo()
    ' declare all the required variables
    Dim counter, input_number As Integer
    
    ' Receive input from user
    input_number = InputBox(" Which tables do you want to print ? ")
    
    ' Print the mathematical table of the input number upto 12 count
    For counter = 1 To 12
        Debug.Print (counter &amp;amp;amp; " X " &amp;amp;amp; input_number &amp;amp;amp; " = " &amp;amp;amp; counter * input_number)
    Next
            
End Sub

This program receives a number as an input from the user. Then, using a “for” loop, it is multiplied with each number from 1 to 12 to print a “times table” table of that input number.

A sample output of this program if “3” is input by the user is seen in the image below.

A sample output of this program if “3” is input by the user.

Program to Print Contents of an Array

This program defines an array with its size. All elements of the array are assigned values one by one. Next they are printed as we iterate through a loop. It is noteworthy to say that the iterator variable (i) of the “for” loop is also used as the array index inside the loop (this is not mandatory but makes it easy to read/understand/maintain).

Sub array_cars()

'declaring variable while defining its size
Dim arr_my_cars1(5) As Variant

'initialize array elements for one array
 arr_my_cars1(0) = "Benz"
 arr_my_cars1(1) = "Maruthi"
 arr_my_cars1(2) = "Hyundai"
 arr_my_cars1(3) = "Ford"
 arr_my_cars1(4) = "Nissan"

'print all elements of the array
For i = LBound(arr_my_cars1) To UBound(arr_my_cars1)
    Debug.Print arr_my_cars1(i)
Next

End Sub

Output of the Program:

Benz

Maruthi

Hyundai

Ford

Nissan

Program to Write and Read Array Contents

This program slightly varies from the one above. Here you will create an array and iterate through it using its indices. 

Values are given to each array item using a “for” loop initially. (This was not the case in the previous program.)

Then, all the data stored in each element of the same array are read/printed back using another “for” loop.

Two loops are used here one below the other:

  1. One to write data to array
  2. Another one to read data from the same array.
Sub array_check_demo1()

' Declaration of array variable
Dim arr1(11)

' Assign values to array elements
For i = LBound(arr1) To UBound(arr1)
    'Allocate data for each array item through a loop
    arr1(i) = Cells(i + 2, 1).Value
Next

' Print values of the array
For i = LBound(arr1) To UBound(arr1)
    'Read data of each array item through a loop
    Debug.Print arr1(i)
Next
End Sub

Input is taken from the table below:

Principal amount No of yrs Age of customer
10000 5 67
340600 6 45
457800 8 34
23400 3 54
12000 4 23
23545 4 56
345243 2 55
34543 3 24
23223 2 19
3656 1 65

Output of the Program

Output of the "for" loop program

Program That Uses the [step] Value

Check out this program and try to find out why the numbers are not continuous in the output:

Sub step_demo()
' declare a counter
Dim p As Integer

'loop through 10 numbers and print them
For p = 1 To 10 step 3
	Debug.Print p
Next 
End Sub

Output of the Program

1

4

7

10

Yes, you might have found that the iterator variable increments by “3” instead of “1” in every iteration. Hence, the numbers printed are skip counted by “3.”

Try the same with different values in the place of [step] to understand it better if you are still confused.

The Nested “For” Loop

A loop within a loop is called a nested loop. 

Structure

Structure of a nested loop within a loop.

Let me explain this structure with colors:

  1. The for loop structure in yellow color is the outermost loop. 
  2. The for loop structure/block in green color is the inner loop for the outermost (yellow color) loop. But it also acts as the outer loop for the “for loop” structure in turquoise color.
  3. The for loop structure in turquoise color is the innermost loop. 

In this way , we can have any number of nested loops. 

But there are ample chances for you to get confused when you see your own code after several days. You will wonder inside which loop is a specific line and what role it plays in the whole code.

To avoid this, follow the tips below while you code your logic:

  1. Maintain the alignment in your code with proper tab spaces as shown in the structure above. This can help you find the block of code/loop in which your statement is. 

If possible, use the iterator variable next to the “next” keyword. It can help you indicate which “next” statement  marks the closure of which loop. This is also marked in the colored structure for reference.

A Few Examples of Nested For Loops

Program to Format Cells with a Specific Word

This program iterates through all the cells (every column of every row in this case). If the cell content has a word “India,” then the specified formatting is applied to it.

Sub format_cell_with()
For i = 1 To 15
    For j = 1 To 5
    cellcontent = Cells(i, j).Value
    If InStr(cellcontent, "India") &amp;amp;gt; 0 Then
        With Cells(i, j).Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorAccent2
        .TintAndShade = 0.399975585192419
        .PatternTintAndShade = 0
        End With
    End If
    Next
Next

Input sheet:

ICC Men’s Cricket World Cup Winners – 50 Overs
Year World Cup Winner Runners Up Host Finals Venue
1975 West Indies Australia England Lord’s Cricket Ground, London
1979 West Indies England England Lord’s Cricket Ground, London
1983 India West Indies England Lord’s Cricket Ground, London
1987 Australia England India & Pakistan Eden Gardens, Kolkata
1992 Pakistan England Australia & New Zealand Melbourne Cricket Ground, Melbourne
1996 Sri Lanka Australia India, Pakistan & Sri Lanka Gaddafi Stadium, Lahore
1999 Australia Pakistan England Lord’s Cricket Ground, London
2003 Australia India Australia Wanderers, Johannesburg
2007 Australia Sri Lanka West Indies Kensington Oval, Bridgetown
2011 India Sri Lanka India Wankhede Stadium, Mumbai
2015 Australia New Zealand Australia Melbourne Cricket Ground
2019 England New Zealand England Lord’s, London
2023 India

Output sheet – after the program is run:

Output sheet after a program to format cells with a specific word is run.

Program with 2D Array and “NESTED FOR” Loop

This program declares a two dimensional array and initializes data in all its elements.

The first dimension holds the students’ names, and the second dimension holds the “exam results” of the students in the first dimension. These are written back to an Excel sheet. 

Warning: As the code does not select any sheet in specific, please ensure that you keep a blank Excel sheet selected. This can prevent any damage to your existing data.

In case you wish to learn more about multidimensional arrays, please check out this article.

Sub Nested_for_demo2()

'declaring and defining size of an array
'3 means 4 rows starting from 0 to 3 and 1 means 2 columns starting from 0 to 1
Dim arr_stu(1 To 5, 1 To 2) As Variant

'initialize array elements

 arr_stu(1, 1) = "Dave"
 arr_stu(1, 2) = "Fail"
 arr_stu(2, 1) = "Trumpo"
 arr_stu(2, 2) = "Pass"
 arr_stu(3, 1) = "Vincent"
 arr_stu(3, 2) = "Pass"
 arr_stu(4, 1) = "Rose Mary"
 arr_stu(4, 2) = "Pass"
 arr_stu(5, 1) = "Eliza"
 arr_stu(5, 2) = "Fail"
 
' print all elements to the open excel sheet.
For i = 1 To 5
    For j = 1 To 2
        Cells(i, j) = arr_stu(i, j)
    Next j
Next

End Sub

Output of the Program on the Active Excel Sheet: Here 

  1. The rows indicate the “i” value of the array (first dimension) and the iterator variable of the outer “for” loop.
  2. The columns indicate the  “j”  value of the array (Col A – first dimension , Col B – second dimension)  and the iterator variable of the inner “for” loop.

The “Continue” Statement in Visual Basic: Skip a Part of an Iteration

When you encounter a situation where you wish to skip running the rest of the code inside the loop for a specific iteration based on a condition, the “continue” statement will come to your rescue in Visual Basic Programming.

Continue

Syntax:

Continue { Do | For | While }

Where  { Do | For | While } are the respective loops in which it has to be used.

A Simple Example

Sub continue_demo()
' declare a counter
Dim i As Integer

'loop through 10 numbers and print them
For i = 1 To 10
    ' we will skip printing "4"
    If i = 4 Then
        Continue For
    End
    Debug.Print i
Next
End Sub

Your output will not have “4” in this case. As the condition is met in the 4th iteration, the continue statement is hit and the rest of the code is skipped for that iteration. The control then moves to the “next” statement of the loop (inner loop in case of nested loops).  

Note: The Next statement is the closure of a loop, as you may be aware.

Output of the above program

1

2

3

5

6

7

8

9

10

Continue Statement is Not Available in VBA

VBA does not offer the “continue statement” because well-built logic in a loop can help us avoid using a “continue” statement. For example, rearranging statement blocks like nested loops and if conditions can help avoid the use of “continue” statements. 

An Alternative to the Continue Statement

In unavoidable situations, the Goto statement can be used

This article can provide you with more insights on how to properly use the “Goto” statement in VBA.

Conclusion

In my experience, I would say that the “for” loop is my favorite compared to the “do while “/“Do until”/“ For each” loops. The reason is the comfort of defining it completely in one line. Even during run-time, you can find how many iterations are completed and how many are yet to come.

I have also been able to use this loop in situations where I do not know the number of iterations. I manage it using conditions inside the loop. It also comes handy when I want to wait for a page load during automation. Once you start using this loop, you will even start playing around nested “for loops” with much more confidence and fewer of mistakes. 

So, what are you waiting for ? Why not give it a try? 😊

If you’re looking to automate your Excel spreadsheets, macros are a good way to do so. Macros are automated scripts, typically written using Visual Basic for Applications (VBA), to help you perform certain actions in Excel, such as automate a button press or perform a calculation.

VBA is a useful programming language for new data analysts to learn as it supercharges the functionality of Excel, making it easier to perform certain tasks automatically (and repeatedly) with custom-made macro scripts. For instance, if you want a macro that repeats an action by a certain number of times, you can use a VBA For Loop.

Loops like this aren’t unique to VBA—indeed, they’re a common feature in most programming languages, allowing a program or script to run continuously in a sequence with a start and end point. For Excel data analysts, a VBA For Loop can allow you to loop through cells or perform a set number of actions once the criteria to do so are met.

This could be once a certain calculation is inserted or value reached, or when you perform a certain action in your spreadsheet itself (such as, for instance, pressing a custom-inserted button). Using a VBA For Loop is essential for creating macros that will run continuously as you work through your spreadsheet.

If you’re new to VBA programming and you’re looking to create a basic (or even advanced) macro using a VBA For Loop, this guide should help you. In this article, we’ll explain:

  1. What are VBA For Loops in Microsoft Excel and what are they used for?
  2. How do VBA For Loops work in Excel?
  3. Things to consider before using a VBA For Loop in Excel
  4. How to add a VBA For Loop in Excel using the Visual Basic Editor

How do VBA For Loops work in Excel? Let’s get familiar with the basics.

1. What are VBA For Loops in Microsoft Excel and what are they used for?

As we’ve mentioned already, loops are a programming concept that allows a program to repeat itself. They help to refract your code, reducing the number of specifically-coded actions that are written to help improve the speed and efficiency of your applications.

Loops are flexible tools, giving you the option to repeat a certain action (such as changing cell values) a set number of times. A loop could also be combined with other statements, such as For and If, that help to determine how often, and for how long, a script should run.

In VBA, a For Loop repeats an action (or set of actions) for a set number of times in a sequence. For instance, if you had a macro (written in VBA) that inserted values into a column, you could use a For Loop to do so, filling each cell sequentially (eg. A1, A2, A3, etc) until an end value is reached.

A VBA code snippet in Microsoft Excel

For instance, the VBA code snippet shown previously demonstrates such an action. In this example, the VBA macro is designed to insert values into cells in column A, from 1 to 10, and increase in single-digit increments. Once 10 is reached, the script stops.

This is a basic example, but For Loops are powerful enough to perform almost any action you desire in Excel repeatedly. While this guide isn’t a full VBA tutorial (and it assumes you have a certain level of basic VBA experience already), it should allow you to create basic VBA loops using For to repeat an action in sequence.

2. How do VBA For Loops work in Excel?

Let’s assume that you already have an idea in mind as to how your VBA macro should work. Introducing a For Loop into the mix allows you to set your code (or part of your code) to repeat itself a certain number of times.

We’ll explain the process using a simple-to-understand example. As VBA For Loops are useful for finite repetitive actions, let’s assume you want a pop-up to appear when you press a button (with the class name Button).

A VBA code snippet in Microsoft Excel, with a pop-up button with the text "Press me!"

Pressing the button causes a pop-up box to appear a set number of times, in sequence, using the variable varButton as the end number (in this case, 10). This pop-up box displays the current variable, starting with zero. It then repeats this 9 more times until the varButton variable (10) is reached.

The action of pressing the button begins the loop. As the test has a start and end variable, the loop has a finite number of runs before it finishes. By default, the values increase by 1 (starting with 0, 1, 2, etc) but this can be changed by adding a Step value. For instance, changing this to 5 would mean only three pop-ups appear.

A Microsoft Excel worksheet with a button with the text "Press me!" and a pop-up window where the Step value has been set to five.

Once the end value is reached, the loop exits and the macro stops. You could, however, add additional actions to perform at this point, such as changing another cell’s value or creating a different pop-up message. You could nest the For Loop within other logical tests, such as a Do While or If statement.

This example contains all of the typical criteria needed to complete a For Loop using VBA, however. The code identifies how many times the action will be performed in a sequence (varButton) and the increment value used to iterate through the sequence (Step).

The only optional part of this example is the button used to start the macro. You don’t necessarily need to link your macro code to a button press, as you could easily begin this loop and activate the macro manually by pressing Developer > Macros > Run instead. 

3. Things to consider before using a VBA For Loop in Excel

A VBA For Loop is a flexible and wide-ranging method that allows your code to perform an action sequentially and only stopping if (and when) certain criteria are met. To help you create this kind of macro in Excel, there are some pointers you’ll need to consider. These include:

  • If you want to create a way for your For Loop to end before the final value is reached, you’ll need to add an Exit For statement to your code. This exits the loop and moves on to the next line of code outside of the loop (if your code continues). For instance, you could stop the loop when you press a button.
  • A VBA For Loop can be used to cycle through a set number of numerical values in sequence in a basic way using a For Next Loop, but you can also cycle through more complex objects (such as workbooks in your spreadsheet) in sequence using a more complex VBA For Each Loop.
  • VBA For Loops can be nested with other logical statements, such as an If or Do While statement. This allows you to integrate more complex decision-making into your code.
  • A VBA For Loop will iterate in a sequence, but by changing the Step value, you can change how much the loop counter increases by during each iteration. For instance, if you want your loop to move ahead in a sequence that increases the value by 2, you’d need to use a Step value of 2. If you don’t provide a Step value, the loop counter will increase in increments of 1.
  • If your VBA For Loop can’t be performed, or if your code has errors, VBA will exit into debug mode with an error. You’ll need to troubleshoot your code to fix this problem in Excel’s built-in VBA Editor.

While these examples are important, you should also consider any known VBA limitations that aren’t listed here (such as a lack of an undo function when using VBA) before you write your code.

4. How to add VBA For Loops in Excel using the Visual Basic Editor

You can create, test, and run a VBA For Loop in Excel by using the Visual Basic Editor. This is Excel’s built-in VBA editor that allows you to create your own macros using VBA, or edit existing macros created using the Macro Recorder tool.

To begin creating a VBA macro using a For Loop in the Visual Basic Editor, you can follow these steps:

Step 1: Open the VBA Editor

You’ll need to start by opening the Visual Basic Editor in your Excel workbook.

You can do this by pressing the Alt + F11 keys on your keyboard (or Option + F11 on Mac). If you’ve already enabled the Developer tab on the ribbon bar in your Excel’s settings menu, you can also press Developer > Visual Basic to open the editor instead.

The ribbon bar in Microsoft Excel, with the developer tab highlighted and an arrow pointing to the Visual Basic icon

Step 2: Create a new VBA Module

The VBA Editor will open in a new window at this point. The next step is to insert your VBA For Loop (and additional code) as a new VBA module. Modules are used to organize VBA code into groups.

To do this, right-click your workbook listed in the tree menu on the left. From the drop-down menu, select Insert > Module.

The VBA editor in Microsoft Excel, which has opened in a separate window. A particular workbook has been selected from the tree menu and “insert” then “module” selected from the subsequent drop-down menu.

Step 3: Insert your VBA For Loop code

A new window for your code will appear on the right. This is where you can type or insert the VBA code containing your For Loop. For instance, the following code will insert sequential values into cells A1 to A20 on any active worksheet:

Sub LoopVal()

Dim i As Integer

For i = 1 To 10

Range(“A” & i).Value = i

Next i

End Sub

VBA For Loop code in the editor window in Microsoft Excel

Step 4: Rename your module and test your code

Once you’ve inserted your code, you’ll need to rename the module which contains the code in order to make it easy to refer to later. To do this, select the module name in the tree menu on the left, then rename it by typing a new module name into the Properties box underneath.

The VBA editor in Microsoft Excel. A specific module has been selected from the tree menu, and renamed "LoopValues"

When you’re ready to test your code, press the Run Sub/User Form button. This will run the code in your active worksheet, allowing you to see the macro in action.

The VBA editor in Microsoft Excel. The Run Sub / User Form has been clicked in order to run the code in the worksheet.

Assuming your VBA code worked as intended, you can then proceed to save your workbook with the macro included. If it doesn’t work, a debug message will appear, and you’ll need to troubleshoot the issue further.

Step 5: Save your workbook

With your VBA macro ready, you’ll need to save your Excel workbook as a Macro-enabled workbook in the XLSM format. To do this, press Ctrl + S on your keyboard, or press File > Save As.

The Microsoft Excel toolbar with file, save as, selected.

Step 6: Run your VBA code

Your macro (containing a VBA For Loop) is ready to run once you’ve saved your workbook. To do this, press Alt + F8 on your keyboard to open the Macro window (or Option + F8 on Mac).

The Macro popup window in Microsoft Excel, with the "run" button highlighted.

Select your macro (matching the Module name) from the list provided, then press Run. Alternatively, if your VBA For Loop is scheduled to activate based on another action (such as a cell value being reached, a button being pressed, etc), you’ll need to perform this action to begin the process.

Final thoughts

Once you’ve mastered VBA For Loops, you can take things further by experimenting with Do Until Loops, custom worksheet events, and more. VBA tricks like these allow data analysts to create complex applications inside Excel workbooks that can automate tasks or speed up calculations, but you’ll need to master VBA first.

If you’re new to Excel or you’re interested in a career in data analysis, our five-day short course can help you learn more about the fundamentals. If you’re curious to learn more about Excel, you can check out these articles next:

  • How to use conditional formatting in Excel
  • How to calculate variance in Excel
  • How to convert texts to numbers in Excel

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.

Понравилась статья? Поделить с друзьями:
  • Excel vba left описание
  • Excel vba for each range in range cells
  • Excel vba last column
  • Excel vba odbc connection
  • Excel vba for each next for