For vba excel описание пример

In this Article

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

To work effectively in VBA, you must understand Loops.

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

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

VBA Loop Quick Examples

For Each Loops

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

Loop Through all Worksheets in Workbook

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

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

Loop Through All Cells in Range

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

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

vba else if statement

For Next Loops

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

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

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

Do While Loops

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

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

Do Until Loops

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

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

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

VBA Loop Builder

vba loop builder

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

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

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

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

VBA For Next Loop

For Loop Syntax

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

[Dim Counter as Integer]

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

Where the items in brackets are optional.

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

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

Count to 10

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

Sub ForEach_CountTo10()

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

End Sub

For Loop Step

Count to 10 – Only Even Numbers

This code will count to 10 only counting even numbers:

Sub ForEach_CountTo10_Even()

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

End Sub

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

VBA Programming | Code Generator does work for you!

For Loop Step – Inverse

Countdown from 10

This code will countdown from 10:

Sub ForEach_Countdown_Inverse()

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

End Sub

Delete Rows if Cell is Blank

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

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

Sub ForEach_DeleteRows_BlankCells()

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

End Sub

Nested For Loop

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

Sub Nested_ForEach_MultiplicationTable()

Dim row As Integer, col As Integer

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

End Sub

vba nested for loop

Exit For

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

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

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

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

Sub ExitFor_Loop()

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

End Sub

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

Continue For

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

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

VBA For Each Loop

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

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

You can also use Nested For Each Loops to:

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

The syntax is:

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

Where:

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

For Each Cell in Range

This code will loop through each cell in a range:

Sub ForEachCell_inRange()

Dim cell As Range

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

End Sub

For Each Worksheet in Workbook

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

Sub ForEachSheet_inWorkbook()

Dim ws As Worksheet

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

End Sub

For Each Open Workbook

This code will save and close all open workbooks:

Sub ForEachWB_inWorkbooks()

Dim wb As Workbook

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

End Sub

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

For Each Shape in Worksheet

This code will delete all shapes in the active sheet.

Sub ForEachShape()

Dim shp As Shape

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

End Sub

For Each Shape in Each Worksheet in Workbook

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

Sub ForEachShape_inAllWorksheets()

Dim shp As Shape, ws As Worksheet

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

End Sub

For Each – IF Loop

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

This code will hide all blank rows in a range:

Sub ForEachCell_inRange()

Dim cell As Range

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

End Sub

VBA Do While Loop

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

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

Here is the Do While Syntax:

Do While Condition
[Do Something]
Loop

Where:

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

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

Do 
[Do Something]
Loop While Condition

We will demo each one and show how they differ:

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

Do While

Here is the Do While loop example we demonstrated previously:

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

Loop While

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

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

VBA Do Until Loop

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

Do Until Condition
[Do Something]
Loop

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

Do 
[Do Something]
Loop Until Condition

Do Until

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

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

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

Loop Until

This Loop Until loop will count to 10:

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

Exit Do Loop

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

Exit Do

Here is an example of Exit Do:

Sub ExitDo_Loop()

Dim i As Integer
i = 1 

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

End Sub

End or Break Loop

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

Exit For
Exit Do

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

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

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

More Loop Examples

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

Loop Through Rows

This will loop through all the rows in a column:

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

Loop Through Columns

This will loop through all columns in a row:

Public Sub LoopThroughColumns()

Dim cell As Range

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

End Sub

Loop Through Files in a Folder

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

Sub LoopThroughFiles ()

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

Set oFSO = CreateObject("Scripting.FileSystemObject")

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

i = 2

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

End Sub

Loop Through Array

This code will loop through the array ‘arrList’:

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

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

Loops in Access VBA

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

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

В этом учебном материале вы узнаете, как использовать Excel оператор FOR … NEXT для создания цикла FOR в VBA с синтаксисом и примерами.

Описание

Оператор Microsoft Excel FOR … NEXT используется для создания цикла FOR, чтобы вы могли выполнять код VBA определенное количество раз. Оператор FOR … NEXT является встроенной функцией Excel, которая относится к категории логических функций. Её можно использовать как функцию VBA в Excel.
В качестве функции VBA вы можете использовать эту функцию в коде макроса, который вводится через редактор Microsoft Visual Basic Editor.

Синтаксис

Синтаксис для создания цикла FOR с использованием оператора FOR … NEXT в Microsoft Excel:

For counter = start To end [Step increment] {…statements…}Next [counter]

Аргументы или параметры

counter
Переменная счетчика цикла.
start
Начальное значение для counter.
end
Конечное значение для counter.
increment
По желанию. Значение counter увеличивается при каждом проходе цикла. Это может быть положительное или отрицательное число.
Если не указано, по умолчанию будет приращение 1, так что каждый проход через цикл увеличивает counter на 1.
statement
Операторы кода для выполнения каждого прохода через цикл.

Возвращаемое значение

Оператор FOR … NEXT создает цикл FOR в VBA.

Примечание

  • См. также инструкцию WHILE … WEND, чтобы создать цикл WHILE в VBA.

Применение

  • Excel для Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 для Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Тип функции

  • Функция VBA

Пример (как функция VBA)

Оператор FOR … NEXT может использоваться только в коде VBA в Microsoft Excel.
Давайте посмотрим, как создать цикл FOR в Microsoft Excel, начиная с одинарного цикла, двойной цикл и тройной цикл, а затем исследуем, как изменить значение, используемое для увеличения счетчика при каждом прохождении цикла.

Одинарный цикл

Простейшей реализацией цикла FOR является использование оператора FOR … NEXT для создания одного цикла. Это позволит вам повторять код VBA фиксированное количество раз, например:

Sub Single_Loop_Example

  Dim LCounter As Integer

  For LCounter = 1 To 5

   MsgBox (LCounter)

  Next LCounter

End Sub

В этом примере цикл FOR управляется переменной LCounter. Он будет повторяться 5 раз, начиная с 1 и заканчивая 5. Каждый раз внутри цикла он будет отображать окно сообщения со значением переменной LCounter. Этот код отобразит 5 окон сообщений со следующими значениями: 1, 2, 3, 4 и 5.

Одинарный цикл — изменение приращения

По умолчанию цикл FOR увеличивает свой счетчик цикла на 1, но это можно настроить. Вы можете использовать Step increment, чтобы изменить значение, используемое для увеличения счетчика. Приращение цикла FOR может иметь как положительные, так и отрицательные значения.

Положительное приращение

Давайте сначала рассмотрим пример того, как увеличить счетчик цикла FOR на положительное значение.
Например:

Sub Increment_Positive_Example

  Dim LCounter As Integer

  For LCounter = 1 To 9 Step 2

   MsgBox LCounter

  Next LCounter

End Sub

В этом примере мы использовали шаг 2 в цикле FOR, чтобы изменить приращение на 2. Это означает, что цикл FOR будет начинаться с 1, увеличиваться на 2 и заканчиваться на 9. Код будет отображать 5 окон сообщений со следующими значениями: 1, 3, 5, 7 и 9.

Отрицательное приращение

Теперь давайте посмотрим, как увеличить счетчик цикла FOR на отрицательное значение.
Например:

Sub Increment_Negative_Example

  Dim LCounter As Integer

  For LCounter = 50 To 30 Step 5

   MsgBox LCounter

  Next LCounter

End Sub

Когда вы увеличиваете на отрицательное значение, вам нужно, чтобы начальное число был с более высоким значением, а конечное число — с меньшим значением, поскольку цикл FOR будет вести обратный отсчет. Итак, в этом примере цикл FOR будет начинаться с 50, увеличиваться на -5 и заканчиваться на 30. Код отобразит 5 окон сообщений со следующими значениями: 50, 45, 40, 35 и 30.

Двойной цикл

Теперь давайте рассмотрим пример создания двойного цикла FOR в Microsoft Excel.
Например:

Sub Double_Loop_Example

  Dim LCounter1 As Integer

  Dim LCounter2 As Integer

  For LCounter1 = 1 To 4

   For LCounter2 = 8 To 9

     MsgBox LCounter1 & «-« & LCounter2

   Next LCounter2

  Next LCounter1

End Sub

Здесь у нас есть 2 цикла FOR. Внешний цикл FOR управляется переменной LCounter1. Внутренний цикл FOR управляется переменной LCounter2. В этом примере внешний цикл FOR будет повторяться 4 раза (начиная с 1 и заканчивая 4), а внутренний цикл FOR будет повторяться 2 раза (начиная с 8 и заканчивая 9). Во внутреннем цикле код будет каждый раз отображать окно сообщения со значением LCounter1-LCounter2. Таким образом, в этом примере будут отображаться 8 окон сообщений со следующими значениями: 1-8, 1-9, 2-8, 2-9, 3-8, 3-9, 4-8 и 4-9.

Тройной цикл

Теперь давайте рассмотрим пример того, как создать тройной цикл FOR в Microsoft Excel.
Например:

Sub Triple_Loop_Example

  Dim LCounter1 As Integer

  Dim LCounter2 As Integer

  Dim LCounter3 As Integer

  For LCounter1 = 1 To 2

   For LCounter2 = 5 To 6

     For LCounter3 = 7 To 8

      MsgBox LCounter1 & «-« & LCounter2 & «-« & LCounter3

     Next LCounter3

   Next LCounter2

  Next LCounter1

End Sub

В приведенном выше примере у нас есть 3 цикла FOR. Самый внешний цикл FOR управляется переменной LCounter1. Следующий цикл FOR управляется переменной LCounter2. Самый внутренний цикл FOR управляется переменной LCounter3. В этом примере самый внешний цикл FOR будет повторяться 2 раза (начиная с 1 и заканчивая 2), следующий цикл FOR будет повторяться 2 раза (начиная с 5 и заканчивается на 6), а самый внутренний цикл FOR будет повторяться 2 раза (начиная с 7 и заканчивая 8). Внутри самого внутреннего цикла код будет каждый раз отображать окно сообщения со значением LCounter1-LCounter2 -LCounter3. Этот код отображает 8 окон сообщений со следующими значениями: 1-5-7, 1-5-8, 1-6-7, 1-6-8, 2-5-7, 2-5-8, 2- 6-7 и 2-6-8.

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

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

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

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

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

Related Links for the VBA For Loop

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

A Quick Guide to the VBA For Loop

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

The VBA For Loop Webinar

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

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

Introduction to the VBA For Loop

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

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

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

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

What are VBA For Loops?

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

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

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

Let’s look at a simple example.

VBA For Loop Example 1

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

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

The Immediate Window

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

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

 
ImmediateWindow

 
ImmediateSampeText

VBA For Loop Example 2

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

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

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

 
The output is:

VBA Excel

Output

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

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

VBA For Loop Example 3

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

 
The way you approach this task is as follows

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

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

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

 
The following screenshot shows an example of this list

Sample Data of Fruit Sales

Sample Data of Fruit Sales

 
We can use the code to count the oranges

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

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

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

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

End Sub

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

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

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

Advantages of the VBA For Loop

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

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

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

The Standard VBA For Loop

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

YouTube Video For Loop

Check out this YouTube Video of the For Loop:

Get the workbook and code for this video here
 

Format of the Standard VBA For Loop

The Standard VBA For Loop has the following format:

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

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

How a For Loop Works

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

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

 
How this code works is as follows

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

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

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

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

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

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

Using Step with the VBA For Loop

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

 
The next example shows you how to do this:

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

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

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

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

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

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

Exit the For Loop

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

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

    For i = 1 To 1000

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

    Next i

Using the VBA For Loop with a Collection

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

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

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

Using Nested For Loops

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

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

 
The following code shows how:

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

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

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

    Next i

End Sub

 
This works as follows:

 
The first loop sets i to 1

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

 
The first loop sets i to 2

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

 
and so on

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

The VBA For Each Loop

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

 
This is a simple example of using the For Each Loop

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

 Format of the VBA For Each Loop

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

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

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

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

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

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

Order of Items in the For Loop

For Each goes through items in one way only.

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

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

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

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

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

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

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

Using the VBA For Each Loop With Arrays

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

 
The following example demonstrates this:

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

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

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

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

End Sub

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

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

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

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

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

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

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

End Sub

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

Using Nested For Each Loops

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

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

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

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

    Next i

End Sub

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

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

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

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

    Next wk

End Sub

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

This code run as follows:

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

How to Loop Through a Range

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

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

VBA For Loop Range

 
The following example shows how we do it:

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

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

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

Summary of the VBA For Loops

The Standard VBA For Loop

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

The VBA For Each Loop

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

What’s Next?

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

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

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

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

Download Workbook

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

VBA has two main loop categories:

  • For…Next Loops
  • Do Loops

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

For…Next VBA Loop

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

Syntax

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

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

Example 1 – Basic Form

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

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

How to create VBA loops in Excel - For Next

Example 2 – Step

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

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

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

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

Example 3 – Nested Loops

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

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

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

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

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

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

Example 4 – Exit For

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

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

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

Example 5 — For Each

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

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

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

How to create VBA loops in Excel - For Each

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

Do VBA Loop

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

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

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

Syntax

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

Or, you can use this syntax:

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

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

Example 1 – Do While

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

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

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

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

How to create VBA loops in Excel - Do Loop

Example 2 — Do Until

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

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

Example 3 – Loop While

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

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

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

Example 4 – Loop Until

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

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

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

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

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

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

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

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

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

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

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

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

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

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

A VBA code snippet in Microsoft Excel

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

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

2. How do VBA For Loops work in Excel?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Step 1: Open the VBA Editor

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

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

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

Step 2: Create a new VBA Module

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

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

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

Step 3: Insert your VBA For Loop code

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

Sub LoopVal()

Dim i As Integer

For i = 1 To 10

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

Next i

End Sub

VBA For Loop code in the editor window in Microsoft Excel

Step 4: Rename your module and test your code

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

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

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

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

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

Step 5: Save your workbook

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

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

Step 6: Run your VBA code

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

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

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

Final thoughts

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

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

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

Понравилась статья? Поделить с друзьями:
  • For using the word god
  • For use of a better word meaning
  • Food with the word dog in it
  • Food with 5 letter word
  • Food which word is odd