Excel do loop exit

Return to VBA Code Examples

In VBA, you can exit a Do loop using the Exit Do command.

Exit Do

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

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

Exit a Loop When a Condition is Met

You will see in the example below how to exit a Do 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 6, we want to exit the loop and return a message box. Here is the code:

Dim i As Integer

Do While i < 10
        i = i + 1
      
        If i = 6 Then
            Exit Do
        End If
Loop

MsgBox "The value is " & i

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

Do While i < 10

Loop

In the body of the loop, we increment the value of i by 1:

i = i + 1

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

If i = 6 Then
    Exit Do
End If

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

MsgBox "The value is " & i

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

vba exit loop

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!

“Now… We are going in a loop” ― Ramakrishna, Springs of Indian Wisdom

 
This post provides a complete guide to the VBA Do While and VBA While Loops. (If you’re looking for information about the VBA For and For Each loops go here)

The VBA While loop exists to make it compatible with older code. However, Microsoft recommends that you use the Do Loop as it is more “structured and flexible”. Both of these loops are covered in this post.

For a quick guide to these loops check out the Quick Guide Table below.

If you are looking for something in particular, you can check out the Table of Contents below(if it’s not visible click on the post header).

A Quick Guide to VBA While Loops

Loop format Description Example
Do While … Loop Runs 0 or more time while condition is true Do While result = «Correct»
Loop
Do … Loop While Runs 1 or more times while condition is true Do
Loop While result = «Correct»
Do Until … Loop Runs 0 or more times until condition is true Do Until result <> «Correct»
Loop
Do … Until Loop Runs 1 or more times until condition is true Do
Loop Until result <> «Correct»
While … Wend Runs 0 or more times while condition is true.

Note: this loop is considered obsolete.

While result = «Correct»
Wend
Exit the Do Loop Exit Do Do While i < 10
   i = GetTotal
   If i < 0 Then
      Exit Do
   End If
Loop

Introduction

If you have never use loops before then you may want to read What are Loops and Why Do You Need Them from my post on the For Loop.

I am going to be mainly concentrating on the Do Loop in this post. As I mentioned above, we have seen the While Wend loop is considered obsolete. For completeness, I have included a section on While Wend later in the post.

So first of all why do we need Do While loops when we already have For loops?

For Loops Versus Do While Loops

When we use a For Loop, we know in advance how many times we want to run it. For example, we may want to run the loop once for each item in a Collection, Array or Dictionary.

 
In the following code example, we know at the start of each loop, how many times it will run.

 
' runs 5 times
For i = 1 To 5

' runs once for each item in the collection
For i = 1 To coll.Count

' runs once for each item in the arr
For i = LBound(arr) To coll.lbound(arr)

' runs once for each value between 1 and the value in lastRow
For i = 1 To lastRow

' runs once for each item in the collection
For Each s In coll

 
The Do Loop is different. The Do Loop runs

  1. While a conditon is true
  2.  
    Or
     

  3. Until a condition is true

 
In other words, the number of times the loops runs is not relevant in most cases.

So what is a condition and how do we use them?

Conditions

A condition is a statement that evaluates to true or false. They are mostly used with Loops and If statements. When you create a condition you use signs like >,<,<>,>=,=.

 
The following are examples of conditions

Condition This is true when
x < 5 x is less than 5
x <= 5 x is less than or equal to 5
x > 5 x is greater than 5
x >= 5 x is greater than or equal to 5
x = 5 x is equal to 5
x <> 5 x does not equal 5
x > 5 And x < 10 x is greater than 5 AND x is less than 10
x = 2 Or x >10 x is equal to 2 OR x is greater than 10
Range(«A1») = «John» Cell A1 contains text «John»
Range(«A1») <> «John» Cell A1 does not contain text «John»

 
You may have noticed x=5 as a condition. This should not be confused with x=5 when used as an assignment.

 
For example

' means: the value 6 will be stored in x
x = 6

' means: is x equal to 6?
If x = 6

' means: is x equal to 6?
Do While x = 6

 
The following table demonstrates how equals is used in conditions and assignments

Using Equals Statement Type Meaning
Loop Until x = 5 Condition Is x equal to 5
Do While x = 5 Condition Is x equal to 5
If x = 5 Then Condition Is x equal to 5
For x = 1 To 5 Assignment Set the value of x to 1, then to 2 etc.
x = 5 Assignment Set the value of x to 5
b = 6 = 5 Assignment and Condition Assign b to the result of condition 6 = 5
x = MyFunc(5,6) Assignment Assign x to the value returned from the function

The Do Loop Format

The Do loop can be used in four ways and this often causes confusion. However, there is only a slight difference in each of these four ways.

 
Do is always at the start of the first line and Loop is always at the end of the last line

Do 
Loop

 
We can add a condition after either line

Do [condition]
Loop

Do 
Loop [condition]

 
The condition is preceded by While or Until which gives us these four possibilities

Do While [condition]
Loop

Do Until [condition]
Loop

Do 
Loop While [condition]

Do 
Loop Until [condition]
 

 
Let’s have a look at some examples to make this clearer.

A Do Loop Example

Imagine you want the user to enter a list of items. Each time the user enters an item you print it to the Immediate Window. When the user enters a blank string, you want the application to end.

In this case the For loop would not be suitable as you do not know how many items the user will enter. The user could enter the blank string first or on the hundredth attempt. For this type of scenario, you would use a Do loop.

 
The following code shows an example of this

    Dim sCommand As String

    Do
        ' Get user input
        sCommand = InputBox("Please enter item")

        ' Print to Immediate Window(Ctrl G to view)
        Debug.Print sCommand

    Loop While sCommand <> ""

 
The code enters the loop and continues until it reaches the “Loop While” line. At this point, it checks whether the condition evaluates to true or false.

  • If the condition evaluates to false then the code exits the loop and continues on.
  • If the condition evaluates to true then the code returns to the Do line and runs through the loop again.

 
The difference between having the condition on the Do line and on the Loop line is very simple

When the condition is on the Do line, the loop may not run at all. So it will run zero or more times.
When the condition is on the Loop line, the loop will always run at least once. So it will run one or more times.

 
In our the last example, the condition is on the Loop line because we always want to get at least one value from the user. In the following example, we use both versions of the loop. The loop will run while the user does not the enter the letter ‘n’

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

    Dim sCommand As String

    ' Condition at start
    Do While sCommand <> "n"
        sCommand = InputBox("Please enter item for Loop 1")
    Loop

    ' Condition at end
    Do
        sCommand = InputBox("Please enter item for Loop 2")
    Loop While sCommand <> "n"

End Sub

 
In the above example, both loops will behave the same.

However, if we set sCommand to ‘n’ before the Do While loop starts, then the code will not enter the loop.

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

    Dim sCommand As String
    sCommand = "n"

    ' Loop will not run as command is "n"
    Do Whilel sCommand <> "n"
        sCommand = InputBox("Please enter item for Loop 1")
    Loop

    ' Loop will still run at least once
    Do
        sCommand = InputBox("Please enter item for Loop 2")
    Loop While sCommand <> "n"

End Sub

 
The second loop in the above example(i.e. Loop While) will always run at least once.

While Versus Until

When you use the Do Loop the condition mush be preceded by Until or While.

Until and While are essentially the opposite of each other. They are used in VBA in a similar way to how they are used in the English language. 

 
For example

  • Leave the clothes on the line Until it rains
  • Leave the clothes on the line While it does not rain

 
another example

  • Stay in bed Until it is light
  • Stay in bed While it is dark

 
yet another example

  • repeat Until the count is greater than or equals ten
  • repeat While the count is less than ten

 
As you can see – using Until and While is just the opposite way of writing the same condition.

Examples of While and Until

The following code shows the ‘While’ and ‘Until’ loops side by side. As you can see the only difference is the condition is reversed. Note: The signs <> means ‘does not equal’.

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

    Dim sCommand As String

    ' Condition at start
    Do Until sCommand = "n"
        sCommand = InputBox("Please enter item for Loop 1")
    Loop

    Do While sCommand <> "n"
        sCommand = InputBox("Please enter item for Loop 1")
    Loop

    ' Condition at end
    Do
        sCommand = InputBox("Please enter item for Loop 2")
    Loop Until sCommand = "n"

    Do
        sCommand = InputBox("Please enter item for Loop 2")
    Loop While sCommand <> "n"

End Sub

 
First loop: will only start if sCommand does not equal ‘n’.
Second loop: will only start if sCommand does not equal ‘n’.
Third loop: will run at least once before checking sCommand.
Fourth loop: will run at least once before checking sCommand.

Example: Checking Objects

An example of where Until and While are useful is for checking objects. When an object has not been assigned it has the value Nothing.

 
So when we declare a workbook variable in the following example it has a value of nothing until we assign it to a valid Workbook

    Dim wrk As Workbook

 
The opposite of Nothing is Not Nothing which can be confusing.

Imagine we have two functions called GetFirstWorkbook and GetNextWorkbook which return some workbook objects. The code will print the name of the workbook until the functions no longer return a valid workbook.

 
You can see the sample code here

    Dim wrk As Workbook
    Set wrk = GetFirstWorkbook()

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

 
To write this code using Do While would be more confusing as the condition is Not Is Nothing

    Dim wrk As Workbook
    Set wrk = GetFirstWorkbook()

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

 
This makes the code clearer and having clear conditions is always a good thing. To be honest this is a very small difference and choosing between While and Until really comes down to a personal choice.

Exit Do Loop

We can exit any Do loop by using the Exit Do statement.

The following code shows an example of using Exit Do

Do While i < 1000
     If Cells(i,1) = "Found" Then 
         Exit Do
     End If
     i = i + 1
Loop 

 
In this case we exit the Do Loop if a cell contains the text “Found”.

While Wend

This loop is in VBA to make it compatible with older code. Microsoft recommends that you use the Do loops as they are more structured.

From MSDN: “The Do…Loop statement provides a more structured and flexible way to perform looping.”

Format of the VBA While Wend Loop

The VBA While loop has the following format

While <Condition>
Wend

While Wend vs Do

The different between the VBA While and the VBA Do Loop is :

  1. While can only have a condition at the start of the loop.
  2. While does not have a Until version.
  3. There is no statement to exit a While loop like Exit For or Exit Do.

 
The condition for the VBA While loop is the same as for the VBA Do While loop. The two loops in the code below perform exactly the same way

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

    Dim sCommand As String

    Do While sCommand <> "n"
        sCommand = InputBox("Please enter item for Loop 1")
    Loop

    While sCommand <> "n"
        sCommand = InputBox("Please enter item for Loop 2")
    Wend

End Sub

 Infinite Loop

Even if you have never written code in your life I’m sure you’ve heard the phrase Infinite Loop. This is a loop where the condition will never be met. It normally happens when you forget to update the count.

 
The following code shows an infinite loop

    Dim cnt As Long
    cnt = 1

    ' Do not run - this is an infinite loop
    Do While cnt <> 5

    Loop

 
In this example cnt is set to 1 but it is never updated. Therefore the condition will never be met – cnt will always be less than 5.

 
In the following code the cnt is being updated each time so the condition will be met.

    Dim cnt As Long
    cnt = 1

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

 
As you can see using a For Loop is safer for counting as it automatically updates the count in a loop. The following is the same loop using For.

    Dim i As Long
    For i = 1 To 4

    Next i

 
This is clearly a better way of doing it. The For Loop sets the initial value, condition and count in one line.

 
Of course it is possible to have an infinite loop using For – It just takes a bit more effort 🙂

    Dim i As Long
    ' DO NOT RUN - Infinite Loop
    For i = 1 To 4
        ' i will never reach 4
        i = 1
    Next i

Dealing With an Infinite Loop

When you have an infinite loop – VBA will not give an error. You code will keep running and the Visual Basic editor will not respond.

In the old days you could break out of a loop by simply pressing Ctrl and Break. Nowadays different Laptops use different key combinations. It is a good idea to know what this is for your laptop so that if an infinite loop occurs you can stop the code easily.

You can also break out of a loop by killing the process. Press Ctrl+Shift+Esc. Under the Processes tab look for Excel/Microsoft Excel. Right-click on this and select “End Process”. This will close Excel and you may lose some work – so it’s much better to use Ctrl+Break or it’s equivalent.

Using Worksheet Functions Instead of Loops

Sometimes you can use a worksheet function instead of using a loop.

For example, imagine you wanted to add the values in a list of cells. You could do this using a loop but it would be more efficient to use the worksheet function Sum. This is quicker and saves you a lot of code.

 
It is very easy to use the Worksheet functions. The following is an example of using Sum and Count

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

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

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

End Sub

 
The following example use a loop to perform the same action. As you can see it is a much longer way of achieving the same goal

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

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

    Debug.Print total
    Debug.Print count

End Sub

Summary

The Do While Loop

  • The Do loop can be used in 4 ways.
  • It can be used with While at the start or end, Do While .. Loop, Do … Loop While
  • It can be used with Until at the start or end, Do Until .. Loop, Do … Loop Until
  • While and Until use the opposite condition to each other.
  • An Infinite loop occurs if your exit condition will never be met.
  • Sometimes using a worksheet function is more efficient than using a loop.

The While Wend Loop

  • The While Wend loop is obsolete and you can use the Do Loop instead.

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 and all the tutorials.

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

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

VBA While Loop

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

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

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

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

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

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

Содержание

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

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

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

Введение

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Условия

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

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

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

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

Например

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

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

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

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

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

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

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

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

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

Do [условие]
Loop

Do 
Loop [условие]

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

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

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

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

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

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

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

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

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

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

 Dim sCommand As String

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

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

    Loop While sCommand <> ""

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

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

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

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

Sub GetInput()

    Dim sCommand As String

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

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

End Sub

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

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

Sub GetInput2()

    Dim sCommand As String
    sCommand = "н"

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

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

End Sub

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

While против Until

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

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

Например:

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

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

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

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

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

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

Примеры Until и While

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

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

Sub GetInput()

    Dim sCommand As String

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

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

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

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

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

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

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

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

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

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

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

Dim wrk As Workbook
    Set wrk = GetFirstWorkbook()

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

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

Dim wrk As Workbook
    Set wrk = GetFirstWorkbook()

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

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

Цикл Exit Do

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

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

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

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

While Wend

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

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

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

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

While <Условие>
Wend

While Wend против Do

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

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

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

Sub GetInput()

    Dim sCommand As String

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

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

End Sub

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

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

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

Dim cnt As Long
    cnt = 1

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

    Loop

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

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

Dim cnt As Long
    cnt = 1

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

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

Dim i As Long
    For i = 1 To 4

    Next i

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

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

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

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

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

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

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

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

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

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

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

Sub WorksheetFunctions()

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

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

End Sub

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

Sub SumWithLoop()

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

    Debug.Print total
    Debug.Print count

End Sub

Резюме

Цикл Do While

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

Цикл While Wend

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

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.

What is VBA Loops in Excel?

A VBA loop in excel is an instruction to run a code or repeat an action multiple times. This action (task) can be repeated for a collection of objects like a range of cells, worksheet or workbook, array, chart of a worksheet, and so on. Since a separate code for each task need not be created, loops work much faster than manual repetition of tasks.

For example, VBA loops can be used to highlight cells containing specific text strings, delete empty rows of a dataset, hide or unhide a worksheet, open or close a workbook, set colors of a chart, and so on.

With loops, one can go through the different objects (elements) one by one. Hence, it is possible to analyze and work with each element.

In VBA, statements are executed sequentially. This implies that the first statement is executed first, followed by the second, the third, and so on. However, a VBA loop executes and repeats a single statement or a group of statements till a particular point is attained.

Loops are usually used in all programming languages.

Table of contents
  • What is VBA Loops in Excel?
    • Top 4 Types of VBA Loops
      • #1–For Next VBA Loop
        • Example #1
      • #2–For Each VBA Loop
        • Example #2
      • #3–Do While VBA Loop
        • Example #3
      • #4–Do Until VBA Loop
        • Example #4
    • Frequently Asked Questions
    • Recommended Articles

Top 4 Types of VBA Loops

There are different types of loops in VBA. The top four are listed as follows:

  1. For Next loop
  2. For Each loop
  3. Do While loop
  4. Do Until loop

Let us discuss each type of Excel VBA loop one by one.

#1–For Next VBA Loop

For Next loop allows to loop through a list of numbers and a collection of objects. These objects include cell ranges, worksheets, workbooks, shapes or other objects on a worksheet.

While looping through a range of cells, the same task is performed for every cell specified in the loop. In the For Next loop, the starting and ending numbers need to be mentioned.

With the For Next loop, the block of code is executed for a specific number of times. Hence, this loop must be used when the number of iterations (repetitions) to be performed is known in advance.

Example #1

We want to insert serial numbers 1 to 10 in cells A1 to A10. This is to be done in the following ways:

a) With the traditional technique

b) With the For Next loop

a) The code to insert the serial numbers in the traditional way is written as follows:

Sub SerialNumber ()

Range(“A1”).Value = 1
Range(“A2”).Value = 2
Range(“A3”).Value = 3
Range(“A4”).Value = 4
Range(“A5”).Value = 5
Range(“A6”).Value = 6
Range(“A7”).Value = 7
Range(“A8”).Value = 8
Range(“A9”).Value = 9
Range(“A10”).Value = 10

End Sub

Here, we have written ten lines of code. However, if 100 or 1000 numbers are to be inserted, it would require several lines of the code. Since this would become very difficult, the For Next VBA loop is used to ease the process.

b) The steps to insert the serial numbers with the For Next VBA loop are listed as follows:

Step 1: Open the macro and declare the variable “i” as an integer.

Sub Insert_Serial_Number ()

Dim i As Integer

End Sub

Step 2: Open the For loop. Specify the start and the end of the loop using the variable “i.” The same is shown in the following image.

Vba For Loop

Step 3: Write the code for the task to be performed. Apply the cells property to insert the serial numbers.

Vba For Loop 1

Step 4: Enter “i” as the row number and “1” as the column number. The variable “i” has already been declared as an integer.

Vba For Loop 2

Step 5: The value of the first cell should be one. So, instead of writing “1,” enter “i” as the value. Every time the Excel VBA loop runs, the value of “i” increases by 1.

Vba For Loop 3

Step 6: Press the F8 key to execute one line of the code at a time. This key is to be pressed till the For loop is reached, as shown in the following image.

Note: With the F8 key, one can observe the impact of every line of the code on the worksheet.

Vba For Loop 4

In the following pointers (step 6a to step 6b), the different values of “i” are discussed.

Step 6a: Place the cursor on “i,” as shown in the following image. The value of “i” appears as zero. Moreover, a line is displayed in yellow with a yellow arrow pointing to it.

The yellow color indicates that this line (shown in the following image) of the code is about to run.

Vba For Loop 5

Step 6b: Press the F8 key again. Place the cursor on “i” and its value appears as 1, as shown in the following image. Since the value of “i” is 1, “cells (i, 1).value = i” implies “cells (1, 1).value = 1.”

i value=2

Step 7: Press the F8 key. The value “1” appears in cell A1, as shown in the following image.

result in A1

Step 8: Press the F8 key again. Excel VBA goes back to the For loop again. This is because the end limit of the variable “i” is set at 10. Place the cursor on “i” and its value appears as 2.

i value =2

Step 9: Likewise, the For Next loop runs ten times. Hence, the serial numbers 1 to 10 are inserted in the cells A1:A10, as shown in the following image.

Vba For Loop 9

#2–For Each VBA Loop

The For Each loop is also known as the For Each-Next loop.

The For Each loop VBA For Each Loop helps the user to inspect and analyze the groups of objects or values individually. It even facilitates performing the specific activity for every object or value by passing a statement or group of statements in this reference.read more of VBA helps in looping through a collection of objects. These objects include worksheets, charts, workbooks, shapes, range of cells, and so on.

With the For Each loop, one can go through every object of a collection and perform a task on it. For example, one can perform tasks on every worksheet of a workbook. This task can be to hide or unhide one or more worksheets.

The For Each VBA loop in Excel is used when the number of objects (or elements) in a collection is not known. Hence, the number of iterations (repetitions) to be performed is not known in advance.

Example #2

We want to perform the following tasks with the help of the For Each loop:

a) Hide all worksheets except the sheet titled “main.”

b) Unhide the hidden worksheets (hidden in task a)

a) The code to hide all the worksheets except the sheet “main” is written as follows:

Sub To_Hide_All_Sheet()

       Dim Ws As Worksheet

       For Each Ws In ActiveWorkbook.Worksheets

              If Ws.Name <> “Main” Then
              Ws.Visible = xlSheetVeryHidden
              End If

       Next Ws

End Sub

b) The code to unhide all the hidden sheets (hidden in task a) is written as follows:

Sub To_UnHide_Specific_Sheet()

       Dim Ws As Worksheet

       For Each Ws In ActiveWorkbook.Worksheets

                  Ws.Visible = xlSheetVisible

       Next Ws

End Sub

#3–Do While VBA Loop

The Do While loop repeats a statement or a block of statements while a given condition is true. In other words, the loop runs as long as the condition is true. Once the condition becomes false, looping stops and VBA exits the loop.

The While condition can be tested either at the start or the end of the loop. This implies that the condition may be checked before the execution of the code block or after it.

The testing of the While condition determines the following:

  • If the condition is false and is tested at the beginning of the loop, the statements inside the loop might not run even once.
  • If the condition is false and is tested at the end of the loop, the statements inside the loop always run at least once.

Note: A condition is any expression which evaluates to the Boolean values, true or false.

Example #3

We want to insert the serial numbers 1 to 10 in cells A1:A10. Use the Do While VBA loop.

The code to insert the specified serial numbers with the Do While loop is written as follows:

Sub Do_While_Example()

         Dim i As Integer

         i = 1
         Do While i < 11
              Cells(i, 1).Value = i
              i = i + 1
Loop

End Sub

The loop runs as long as “i” is less than 11. So, the code keeps inserting the serial numbers till i<11. The moment “i” becomes 11, looping stops.

#4–Do Until VBA Loop

The Do Until VBA loop in excel repeats a statement or a block of statements until a specified condition is true. In other words, the loop runs as long as the condition is false. Looping stops once the condition becomes true.

Like the While condition, the Until condition can also be tested either at the start or the end of the loop.

The testing of the Until condition determines the following:

  • If the condition is true and is checked at the beginning of the loop, the statements inside the loop might not run even once.
  • If the condition is true and is checked at the end of the loop, the statements inside the loop will always run at least once.

Note 1: To specify a condition, either While or Until can be used. However, both of them cannot be used together.

Note 2: The Do VBA loop is used when a statement or a block of statements need to be repeated for an indefinite number of times. This repetition of statements is subject to the fulfillment or non-fulfillment of a condition.

Example #4

We want to insert serial numbers 1 to 10 in cells A1:A10. Use the Do Until VBA loop.

The code to insert the given serial numbers with the Do Until loop is written as follows:

Sub Do_Until_Example()

         Dim i As Integer

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

End Sub

The loop runs as long as “i” is less than 11. Once “i” becomes 11, the looping ends. This is because, at i=11, the Until condition becomes true.

The difference between the codes (written in examples #3 and #4) of the Do While and Do Until loops is in the use of the logical operator. In the former, the “less than” operator (<) is used, while in the latter the “equal to” operator (=) is used.

Frequently Asked Questions

1. Define VBA loops.

A VBA loop is an instruction which helps repeat an action multiple times. In other words, the statements are executed more than one time. The number of iterations (repetitions) may be fixed or flexible depending on the kind of loop used.

For example, the iterations of the For Next loop are usually fixed, while those of the Do loops are not fixed.

A loop helps in going through a number of objects and analyzing each one of them. These objects can be cell ranges, workbooks, worksheets, charts, and so on. Loops are preferred in VBA because of their speed. It is much faster and easier to work with loops than repeating tasks manually.

2. What are the various types of loops in VBA and when should they be used?

The various kinds of loops and their uses are stated as follows:

a. For Next loop: It is used when a statement or a group of statements are to be repeated a specified number of times.
b. For Each loop: It is used when a statement or a group of statements are to be repeated for every object (element) in a collection.
c. Do While loop: It is used when a statement or a group of statements are to be repeated as long as the condition is true. The looping ends when the condition ceases to be true.
d. Do Until loop: It is used when a statement or a group of statements are to be repeated as long as the condition is false. The looping ends when the condition becomes true.
e. While Wend loop: It is used when a statement or a group of statements are to be repeated as long as a specified condition is true. This loop was created for compatibility with the earlier languages.

Note: The While Wend loop is not as flexible as the Do While loop. Hence, it is recommended to use the Do While loop instead of the While Wend loop.

3. How to exit the Do loop of VBA?

To exit the Do loop, place the Exit Do statement anywhere inside the Do loop. Usually, an Exit Do statement is inserted after a condition has been evaluated.

The loops Do While and Do Until can be exited with the help of the Exit Do statement. The Exit Do statement is often used in the following situations:

• When it is not required to continue the iterations further
• When a condition has caused the loop to run infinitely

With the Exit Do statement, control is transferred to the statement that immediately follows the loop. The Exit Do statement creates an alternate way to exit the Do loop.

Recommended Articles

This has been a guide to VBA loops. Here we discuss the top 4 types of Excel VBA loops (For Next, For Each, Do While, and Do Until) with examples and practical uses. Other useful articles related to VBA can be found here-

  • Break For Loop in Excel VBAEvery loop in any procedure is given some set of instructions or criteria for it to run a specific number of times, but it is very common for some loops to get into an infinite loop, thus, corrupting the code. In such scenarios, we require VBA Break For Loop to get out of specific situations.read more
  • VBA RangeRange is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.read more
  • Arrays in VBA
  • VLookup in VBA
  • VBA LCaseVBA LCase converts an input string provided to it in the lowercase. The one thing to keep in mind is that this function converts all the function to lowercase, not just any single character.read more

Do loops allow you to repeat code over and over again.  All you need to do is put your code between the Do and Loop statements.

5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!

Structure for a Do Loop

Do
	Set of Instructions
Loop

A Do Loop normally needs some kind of condition or rule to tell it whether to keep looping or when to stop, otherwise it will keep looping forever. You can use Do While or Do Until statements to set the condition.

Do While your condition
	Set of instructions
Loop

Or

Do 
	Set of instructions
Loop While your condition

Note the Loop While version will always perform the first loop, whereas the Do While version will only perform the first loop if the condition is met.

Do Loop Without Criteria Example

In this example the Do Loop will format cells with a green background.  As there is no condition to tell the loop when it should stop it will keep formatting cells until it reaches the bottom of column A.

Sub DoLoopWithoutCriteria()
Range("A1").Select
Do
    ActiveCell.Interior.Color = vbGreen
    ActiveCell.Offset(1, 0).Select
Loop
End Sub

Do Loop With Criteria Examples

5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!

In the following examples we only want the cells with values less than 10 to be formatted with a green background.

The following examples relates to the data shown below.

This example uses a Do Until statement to set a condition.

Sub DoUntil()
Range("A1").Select
Do Until ActiveCell = 10
    ActiveCell.Interior.Color = vbGreen
    ActiveCell.Offset(1, 0).Select
Loop
End Sub

The next example uses a Do While statement to set a condition.

Sub DoWhile()
Range("A1").Select
Do While ActiveCell < 10
    ActiveCell.Interior.Color = vbGreen
    ActiveCell.Offset(1, 0).Select
Loop
End Sub

The final example uses and an If with an Exit Do statement to set a condition.

Sub LoopWithExitDo()
Range("A1").Select
Do
    If ActiveCell = 10 Then Exit Do
    ActiveCell.Interior.Color = vbGreen
    ActiveCell.Offset(1, 0).Select
Loop
End Sub

5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!

Do While Vs Loop While

5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!

Be careful how you use Loop While or Loop Until.  For example the procedure below would format the first cell with a green background even though it doesn’t meet the Loop While criteria. This is because the first loop will always be performed when you use a Loop While or Loop Until loop.

Sub DoWhileVsLoopWhile()
Dim x As Byte
x = 1
    Do
        Cells(x, 1).Interior.Color = vbGreen
        x = x + 1
    Loop While Cells(x, 1) < 10      
End Sub

The code above relates to the data shown below.

Random Numbers Example

In this example the user specifies how many loops the Do Until loop should perform. The variable x is used to store the number of loops that have occurred.

Sub RandomNumbers()
Dim x As Byte
Dim NumberofRandomNumbers As Long
NumberofRandomNumbers = InputBox("How many random numbers do you need?")
Range("A2").Activate
Do Until x = NumberofRandomNumbers
    ActiveCell.Offset(x, 0) = WorksheetFunction.RandBetween(1, 100)
    x = x + 1
Loop
End Sub

Transpose Records Example

A classic use of the Do loop is to perform the same set of actions in a worksheet until the code reaches an empty cell.  In this example we want to transpose data so it appears in database format.

Sub TransposeRecords()
Range("A3").Select

Do While ActiveCell <> Empty
    ActiveCell.Resize(13, 1).Copy
    ActiveCell.Offset(-1, 0).PasteSpecial Transpose:=True
    ActiveCell.Offset(1, 0).Resize(13, 1).EntireRow.Delete
    ActiveCell.Offset(1, 0).EntireRow.Insert
    ActiveCell.Offset(2, 0).Select
Loop

End Sub

The code above relates to the data shown below.

Archive Records Example

5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!

This example archives training records to another worksheet. See code comments for explanation.

Sub ArchiveRecords()
'Create a new worksheet called Archived Records
Worksheets.Add(after:=Worksheets("Training Records")).Name = "Archived Records"
'Copy the headings to the Archived Records worksheet
Worksheets("Training Records").Range("A1").Resize(1, 3).Copy
With Worksheets("Archived Records").Range("A1")
    .PasteSpecial xlPasteColumnWidths
    .PasteSpecial
End With
'Sort the data in date order
Worksheets("Training Records").Activate
Range("A1").CurrentRegion.Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlYes

Range("A2").Select
'Loop through all training records and archive past records
Do While ActiveCell.Value < Date
    ActiveCell.Resize(1, 3).Copy
    Worksheets("Archived Records").Activate
    ActiveCell.Offset(1, 0).PasteSpecial
    Worksheets("Training Records").Activate
    ActiveCell.EntireRow.Delete
Loop

Application.CutCopyMode = False
End Sub

The code above relates to the data shown below.

To get the most out of Excel and VBA, you need to know how to use loops efficiently.

In VBA, loops allow you to go through a set of objects/values and analyze it one by one. You can also perform specific tasks for each loop.

Here is a simple example of using VBA loops in Excel.

Suppose you have a dataset and you want to highlight all the cells in even rows. You can use a VBA loop to go through the range and analyze each cell row number. If it turns out to be even, you give it a color, else you leave it as is.

Now this, of course, is very simple of looping in Excel VBA (and you can also do this using conditional formatting).

In real life, you can do a lot more with VBA loops in Excel that can help you automate tasks.

Here are some more practical examples where VBA loops can be useful:

  • Looping through a range of cells and analyzing each cell (highlight cells with a specific text in it).
  • Looping through all the worksheets and do something with each (such as protect/unprotect it).
  • Loop through all the open workbooks (and save each workbook or close all except the active workbook).
  • Loop through all the characters in a cell (and extract the numeric part from a string).
  • Loop through all the values an array.
  • Loop through all the charts/objects (and give a border or change the background color).

Now to best use loops in Excel VBA, you need to know about the different kinds that exist and the correct syntax of each.

Using Loops in Excel VBA - The Ultimate Guide

In this tutorial, I’ll showcase different types of Excel VBA loops and cover a few examples for each loop

Note: This is going to be a huge tutorial, where I will try and cover each VBA loop in some detail. I recommend you bookmark this page for future reference.

If you’re interested in learning VBA the easy way, check out my Online Excel VBA Training.

For Next Loop

The ‘For Next’ loop allows you to go through a block of code for the specified number of times.

For example, if I ask you to add the integers from 1 to 10 manually, you would add the first two numbers, then add the third number to the result, then add the fourth number to the result, as so on..

Isn’t it?

The same logic is used in the For Next loop in VBA.

You specify how many times you want the loop to run and also specify what you want the code to do each time the loop is run.

Below is the syntax of the For Next loop:

For Counter = Start To End [Step Value]
[Code Block to Execute]
Next [counter]

In the For Next loop, you can use a Counter (or any variable) that will be used to run the loop. This counter allows you to run this loop for a required number of times.

For example, if I want to add the first 10 positive integers, then my Counter value would be from 1 to 10.

Let’s have a look at a few examples to better understand how For Next loop works.

Example 1 – Adding the first 10 positive integers

Below is the code that will add the first 10 positive integers using a For Next loop.

It will then display a message box showing the sum of these numbers.

Sub AddNumbers()
Dim Total As Integer
Dim Count As Integer
Total = 0
For Count = 1 To 10
Total = Total + Count
Next Count
MsgBox Total
End Sub

In this code, the value of Total is set to 0 before getting into the For Next loop.

Once it gets into the loop, it holds the total value after every loop. So after the first loop, when Counter is 1, ‘Total’ value becomes 1, and after the second loop it becomes 3 (1+2), and so on.

And finally, when the loop ends, ‘Total’ variable has the sum of the first 10 positive integers.

A MsgBox then simply displays the result in a message box.

Example 2 – Adding the first 5 Even Positive Integers

To sum the first five even positive integers (i.e, 2,4,6,8, and 10), you need a similar code with a condition to only consider the even numbers and ignore the odd numbers.

Here is a code that will do it:

Sub AddEvenNumbers()
Dim Total As Integer
Dim Count As Integer
Total = 0
For Count = 2 To 10 Step 2
Total = Total + Count
Next Count
MsgBox Total
End Sub

Note that we started the Count value from 2 and also used ‘Step 2‘.

When you use ‘Step 2’, it tells the code to increment the ‘Count’ value by 2 every time the loop is run.

So the Count value starts from 2 and then becomes 4, 6, 8 and 10 as the looping occurs.

NOTE: Another way of doing this could be to run the loop from 1 to 10 and within the loop check whether the number is even or odd. However, using Step, in this case, is a more efficient way as it does not require the loop to run 10 times, but only 5 times.

The Step value can also be negative. In such as case, the Counter starts at a higher value and keeps getting decremented by the specified Step value.

Example 3 – Entering Serial Number in the Selected Cells

You can also use the For Next loop to go through a collection of objects (such as cells or worksheets or workbooks),

Here is an example that quickly enters serial numbers in all the selected cells.

Sub EnterSerialNumber()
Dim Rng As Range
Dim Counter As Integer
Dim RowCount As Integer
Set Rng = Selection
RowCount = Rng.Rows.Count
For Counter = 1 To RowCount
ActiveCell.Offset(Counter - 1, 0).Value = Counter
Next Counter
End Sub

The above code first counts the number of selected rows and then assigns this value to the variable RowCount. We then run the loop from ‘1 to RowCount’.

Also note that since selection can be any number of rows, we have Set the variable Rng to Selection (with the line ‘Set Rng = Selection’). Now we can use the ‘Rng’ variable to refer to the selection in our code.

Example 4 – Protect All Worksheets in the Active Workbook

You can use the ‘For Next’ loop to go through all the worksheets in the active workbook, and protect (or unprotect) each of the worksheets.

Below is the code that will do this:

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

The above code counts the number of sheets by using ActiveWorkbook.Worksheets.Count. This tells VBA how many times the loop needs to be run.

In each instance, it refers to the Ith workbook (using Worksheets(i)) and protects it.

You can use this same code to Unprotect worksheets too. Just change the line Worksheets(i).Protect to Worksheets(i).UnProtect.

Nested ‘For Next’ Loops

You can use nested ‘For Next’ loops to get more complex automation done in Excel. A nested ‘For Next’ loop would mean that there is a ‘For Next’ loop within a ‘For Next’ loop.

Let me show you how to use this using an example.

Suppose I have 5 workbooks open in my system and I want to protect all the worksheets in all these workbooks.

Below is the code that will do this:

Sub ProtectWorksheets()
Dim i As Integer
Dim j As Integer
For i = 1 To Workbooks.Count
For j = 1 To Workbooks(i).Worksheets.Count
Workbooks(i).Worksheets(j).Protect
Next j
Next i
End Sub

The above is a nested For Next loop as we have used one For Next loop within another.

‘EXIT For’ Statements in For Next Loops

‘Exit For’ statement allows you to exit the ‘For Next’ loop completely.

You can use it in cases where you want the For Next loop to end when a certain condition is met.

Let’s take an example where you have a set of numbers in Column A and you want to highlight all the negative numbers in red font. In this case, we need to analyze each cell for its value and then change the font color accordingly.

But to make the code more efficient, we can first check if there are any negative values in the list or not. If there are no negative values, we can use the Exit For the statement to simply come out of the code.

Below is the code that does this:

Sub HghlightNegative()
Dim Rng As Range
Set Rng = Range("A1", Range("A1").End(xlDown))
Counter = Rng.Count
For i = 1 To Counter
If WorksheetFunction.Min(Rng) >= 0 Then Exit For
If Rng(i).Value < 0 Then Rng(i).Font.Color = vbRed
Next i
End Sub

When you use the ‘Exit For’ statement within a nested ‘For Next’ loop, it will come out of the loop in which it is executed and go on to execute the next line in the code after the For Next loop.

For example, in the below code, the ‘Exit For’ statement will get you out of the inner loop, but the outer loop would continue to work.

Sub SampleCode()
For i = 1 To 10
For j = 1 to 10
Exit For
Next J
Next i
End Sub

Do While Loop

A ‘Do While’ loop allows you to check for a condition and run the loop while that condition is met (or is TRUE).

There are two types of syntax in the Do While Loop.

Do [While condition]
[Code block to Execute]
Loop

and

Do
[Code block to Execute]
Loop [While condition]

The difference between these two is that in the first, the While condition is checked first before any code block is executed, and in the second case, the code block is executed first and then the While condition is checked.

This means that if the While condition is False is both the cases, the code will still run at least once in the second case (as the ‘While’ condition is checked after the code has been executed once).

Now let’s see some examples of using Do While loops in VBA.

Example 1 – Add First 10 Positive Integers using VBA

Suppose you want to add the first ten positive integers using the Do While loop in VBA.

To do this, you can use the Do While loop until the next number is less than or equal to 10. As soon as the number is greater than 1o, your loop would stop.

Here is the VBA code that will run this Do While loop and the show the result in a message box.

Sub AddFirst10PositiveIntegers()
Dim i As Integer
i = 1
Do While i <= 10
Result = Result + i
i = i + 1
Loop
MsgBox Result
End Sub

The above loop continues to work until the value of ‘i’ becomes 11. As soon as it becomes 11, the loop ends (as the While condition becomes False).

Within the loop, we have used a Result variable that holds the final value Once the loop is completed, a message box shows the value of the ‘Result’ variable.

Example 2 –  Enter Dates For the Current Month

Let’s say you want to enter all the dates of the current month into a worksheet column.

You can do that by using the following Do While loop code:

Sub EnterCurrentMonthDates()
Dim CMDate As Date
Dim i As Integer
i = 0
CMDate = DateSerial(Year(Date), Month(Date), 1)
Do While Month(CMDate) = Month(Date)
Range("A1").Offset(i, 0) = CMDate
i = i + 1
CMDate = CMDate + 1
Loop
End Sub

The above code would enter all the dates in the first column of the worksheet (starting from A1). The loops continue till the Month value of the variable ‘CMDate’ matches that of the current month.

Exit Do Statement

You can use the Exit Do statement to come out of the loop. As soon as the code executes the ‘Exit Do’ line, it comes out of the Do While loop and passes the control to the next line right after the loop.

For example, if you want to enter the first 10 dates only, then you can exit the loop as soon as the first 10 dates are entered.

The below code will do this:

Sub EnterCurrentMonthDates()
Dim CMDate As Date
Dim i As Integer
i = 0
CMDate = DateSerial(Year(Date), Month(Date), 1)
Do While Month(CMDate) = Month(Date)
Range("A1").Offset(i, 0) = CMDate
i = i + 1
If i >= 10 Then Exit Do
CMDate = CMDate + 1
Loop
End Sub

In the above code, the IF statement is used to check if the value of i is greater than 10 or not. As soon as the value of ‘i’ becomes 10, Exit Do statement is executed and the loop ends.

Do Until Loop

‘Do Until’ loops are very much like the ‘Do While’ loops.

In ‘Do While’, the loop runs till the given condition is met, while in ‘Do Until’, it loops until the specified condition is met.

There are two types of syntax in the Do Until Loop.

Do [Until condition]
[Code block to Execute]
Loop

and

Do
[Code block to Execute]
Loop [Until condition]

The difference between these two is that in the first, the Until condition is checked first before any code block is executed, and in the second case, the code block is executed first and then the Until condition is checked.

This means that if the Until condition is TRUE is both cases, the code will still run at least once in the second case (as the ‘Until’ condition is checked after the code has been executed once).

Now let’s see some examples of using Do Until loops in VBA.

Note: All the examples for Do Until are the same as that of Do While. These have been modified to show you how the Do Until loop works.

Example 1 – Add First 10 Positive Integers using VBA

Suppose you want to add the first ten positive integers using the Do Until loop in VBA.

To do this, you need to run the loop until the next number is less than or equal to 10. As soon as the number is greater than 1o, your loop would stop.

Here is the VBA code that will run this loop and show the result in a message box.

Sub AddFirst10PositiveIntegers()
Dim i As Integer
i = 1
Do Until i > 10
Result = Result + i
i = i + 1
Loop
MsgBox Result
End Sub

The above loop continues to work until the value of ‘i’ becomes 11. As soon as it becomes 11, the loop ends (as the ‘Until’ condition becomes True).

Example 2 –  Enter Dates For the Current Month

Let’s say you want to enter all the dates of the current month into a worksheet column.

You can do that by using the following Do Until loop code:

Sub EnterCurrentMonthDates()
Dim CMDate As Date
Dim i As Integer
i = 0
CMDate = DateSerial(Year(Date), Month(Date), 1)
Do Until Month(CMDate) <> Month(Date)
Range("A1").Offset(i, 0) = CMDate
i = i + 1
CMDate = CMDate + 1
Loop
End Sub

The above code would enter all the dates in the first column of the worksheet (starting from A1). The loop continues until the Month of variable CMDate is not equal to that of the current month.

Exit Do Statement

You can use the ‘Exit Do’ statement to come out of the loop.

As soon as the code executes the ‘Exit Do’ line, it comes out of the Do Until loop and passes the control to the next line right after the loop.

For example, if you want to enter the first 10 dates only, then you can exit the loop as soon as the first 10 dates are entered.

The below code will do this:

Sub EnterCurrentMonthDates()
Dim CMDate As Date
Dim i As Integer
i = 0
CMDate = DateSerial(Year(Date), Month(Date), 1)
Do Until Month(CMDate) <> Month(Date)
Range("A1").Offset(i, 0) = CMDate
i = i + 1
If i >= 10 Then Exit Do
CMDate = CMDate + 1
Loop
End Sub

In the above code, as soon as the value of ‘i’ becomes 10, Exit Do statment is executed and the loop ends.

For Each

In VBA, you can loop through a set of collections using the ‘For Each’ loop.

Here are some examples of collections in Excel VBA:

  • A collection of all the open Workbooks.
  • A collection of all worksheets in a workbook.
  • A collection of all the cells in a range of selected cells.
  • A collection of all the charts or shapes in the workbook.

Using the ‘For Each’ loop, you can go through each of the objects in a collection and perform some action on it.

For example, you can go through all the worksheets in a workbook and protect these, or you can go through all the cells in the selection and change the formatting.

With the ‘For Each’ loop (also referred to as the ‘For Each-Next’ loop), you don’t need to know how many objects are there in a collection.

‘For Each’ loop would automatically go through each object and perform the specified action. For example, if you want to protect all the worksheets in a workbook, the code would be the same whether you have a workbook with 3 worksheets or 30 worksheets.

Here is the syntax of For Each-Next loop in Excel VBA.

For Each element In collection
[Code Block to Execute]
Next [element]

Now let’s see a couple of examples of using the For Each Loop in Excel.

Example 1 – Go through All the Worksheets in a Workbook (and Protect it)

Suppose you have a workbook where you want to protect all the worksheets.

Below For Each-Next loop can do this easily:

Sub ProtectSheets()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Protect
Next ws
End Sub

In the above code, we have defined ‘ws’ variable as a Worksheet object. This tells VBA that ‘ws’ should be interpreted as a worksheet object in the code.

Now we use the ‘For Each’ statement to go through each ‘ws’ (which is a worksheet object) in the collection of all the worksheets in the active workbook (given by ActiveWorkbook.Worksheets).

Note that unlike other loops where we have tried to protect all the worksheets in a workbook, here we don’t need to worry about how many worksheets are there in the workbook.

We don’t need to count these to run the loop. For Each loop ensures that all the objects are analyzed one by one.

Example 2 – Go through All the Open Workbooks (and Save All)

If you work with multiple workbooks at the same time, it can come in handy to be able to save all these workbooks at once.

Below VBA code can do this for us:

Sub SaveAllWorkbooks()
Dim wb As Workbook
For Each wb In Workbooks
wb.Save
Next wb
End Sub

Note that in this code, you don’t get a prompt that asks you to save the workbook in a specific location (if saving it for the first time).

It saves it in the default folder (it was the ‘Documents’ folder in my case). This code works best when these files are already saved and you’re making changes and you want to save all the workbooks quickly.

Example 3 – Go through All the Cells in a Selection (Highlight negative values)

Using the ‘For Each’ loop, you can loop through all the cells in a specific range or in the selected range.

This can be helpful when you want to analyze each cell and perform an action based on it.

For example, below is the code that will go through all the cells in the selection and change the cell color of the cells with negative values to red.

Sub HighlightNegativeCells()
Dim Cll As Range
For Each Cll In Selection
If Cll.Value < 0 Then
Cll.Interior.Color = vbRed
End If
Next Cll
End Sub

(Note I’ve used Cll as a short variable name for Cell. It’s advisable not to use object names such as Sheets or Range as variable names)

In the above code, the For Each-Next loop goes through the collection of cells in the selection. IF statement is used to identify if the cell value is negative or not. In case it is, the cell is given a red interior color, else it goes to the next cell.

In case you don’t have a selection, and instead want VBA to select all the filled cells in a column, starting from a specific cell (just like we use Control + Shift + Down arrow key to select all filled cells), you can use the below code:

Sub HighlightNegativeCells()
Dim Cll As Range
Dim Rng As Range
Set Rng = Range("A1", Range("A1").End(xlDown))
For Each Cll In Rng
If Cll.Value < 0 Then
Cll.Interior.Color = vbRed
End If
Next Cll
End Sub

In the above example, it doesn’t matter how many filled cells are there. It will start from cell A1 and analyze all the contiguous filled cells in the column.

You also don’t need to have cell A1 selected. You can have any far-off cell selected and when the code runs, it will still consider all the cells in column A (starting from A1) and color the negative cells.

‘Exit For’ Statment

You can use the ‘Exit For’ statement in the For Each-Next loop to come out of the loop. This is usually done in case a specific condition is met.

For example, in Example 3, as we are going through a set of cells, it can be more efficient to check if there are any negative values or not. In case there are no negative values, we can simply exit the loop and save some VBA processing time.

Below is the VBA code that will do this:

Sub HighlightNegativeCells()
Dim Cll As Range
For Each Cll In Selection
If WorksheetFunction.Min(Selection) >= 0 Then Exit For
If Cll.Value < 0 Then
Cll.Interior.Color = vbRed
End If
Next Cll
End Sub

Where to Put the VBA Code

Wondering where the VBA code goes in your Excel workbook?

Excel has a VBA backend called the VBA editor. You need to copy and paste the code in the VB Editor module code window.

Here are the steps to do this:

  1. Go to the Developer tab.IF Then Else in Excel VBA - Developer Tab in ribbon
  2. Click on the Visual Basic option. This will open the VB editor in the backend.Click on Visual Basic
  3. In the Project Explorer pane in the VB Editor, right-click on any object for the workbook in which you want to insert the code. If you don’t see the Project Explorer go to the View tab and click on Project Explorer.
  4. Go to Insert and click on Module. This will insert a module object for your workbook.VBA Loops - inserting module
  5. Copy and paste the code in the module window.VBA Loops - inserting module

You May Also Like the Following Excel Tutorials:

  • How to record a macro in Excel.
  • Creating User-defined functions in Excel.
  • Excel VBA Msgbox
  • How to Run a Macro in Excel.
  • How to Create and Use Add-ins in Excel.
  • Excel VBA Events – An Easy (and Complete) Guide.
  • How to Sort Data in Excel using VBA (A Step-by-Step Guide).
  • 24 Useful Excel Macro Examples for VBA Beginners (Ready-to-use).
  • How to Use Excel VBA InStr Function (with practical EXAMPLES).
  • Excel Personal Macro Workbook | Save & Use Macros in All Workbooks.
  • Using Select Case in Excel VBA.

Понравилась статья? Поделить с друзьями:
  • Excel do loop continue
  • Excel english language pack
  • Excel dlya windows 10
  • Excel english 5 grade
  • Excel divide text in cell