VBA For Loop - A Complete Guide - Excel Macro Mastery
VBA For Loop - A Complete Guide - Excel Macro Mastery
Webinars About
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.
Contents [hide]
10 What’s Next?
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.
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 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)
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.
For i = 1 To 20
Debug.Print i
Next i
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.
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.
' https://excelmacromastery.com/
Sub CountFruit()
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.
In the next sections we will look at the different types of loops and how to use them.
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.
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
Dim i As Long
i = i + 1
Debug.Print i
i = i + 1
Debug.Print i
i = i + 1
Debug.Print i
You can use a negative number with Step which will count in reverse
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.
If Step is negative then the start number must be greater than the end number.
You can use Exit For to automatically leave the loop as shown in the following code
For i = 1 To 1000
Next i
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
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.
' https://excelmacromastery.com/
Sub ListWorksheets()
Next i
End Sub
The second loop then uses the workbook at 1 to go through the worksheets.
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.
Dim wk As Workbook
For Each wk In Workbooks
Debug.Print wk.FullName
Next wk
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.
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
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:
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:
Dim s As Variant
For Each s In arr
' Changes what s is referring to - not value of array item
s = "Z"
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()
Dim i As Long
For i = LBound(arr) To UBound(arr)
' Changes value at position to Z
arr(i) = "Z"
Next
End Sub
If your Collection is storing Objects the you can change the items using a For Each loop.
' https://excelmacromastery.com/
Sub ListWorksheets()
Next i
End Sub
This time we will use the For Each loop to perform the same task:
' https://excelmacromastery.com/
Sub ReadAllWorksheets()
Next wk
End Sub
As you can see this is a neater way of performing this task than using the For Loop:
' Read through an Excel Range using the VBA For Loop
' https://excelmacromastery.com/
Sub ForLoopThroughRange()
' Read through all the rows using the For Loop
Dim i As Long
For i = 2 To rg.Rows.Count
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
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.)
40 Comments
K-Li-Ch on April 3, 2015 at 1:30 am
Paul:
to
Sincerely yours,
K-Li-Ch
Reply
Paul Kelly on April 3, 2015 at 6:25 pm
Thanks K-Li-Ch,
Paul
Reply
Paul Kelly on April 16, 2016 at 11:55 am
Reply
Sincerely,
K-Li-Ch
Reply
‘ Print total
MsgBox “Total oranges sold was = ” & Total
End Sub
////////////////////////
Hi Paul!
I’m having a situation where I want to use the total gain from this looping to
another excel workbook and at the same time I don’t want to use the
msgbox but just want the result and put it on another workbook. Is there’s
any possibilities that I can do that? What should I add to the code? I have
tried some of this;
Source_Workbook.Sheets(1).Cells(19, 4) = Target_Data
but it seems not to work out well. Can you help me with this?
Reply
Target_Workbook.Sheets(1).Cells(19, 4) = Target_Data
Reply
Nicolas on April 3, 2017 at 3:50 pm
Hi Paul,
Is there a way to create n for loops without typing manually every loop?
Thanks
Reply
Paul Kelly on April 4, 2017 at 3:03 am
Hi Nicolas.
Reply
Ashish Pawar on July 25, 2017 at 12:43 pm
I have 2 worksheets with one single column common in both which is the
1st column of both worksheets. I want to match the columns in both sheets
and for matching columns ( i.e. for Sheet1.Ax = Sheet2.Ax) I want all rows in
that row from Sheet 2 to the last row column of the sheet 1 . I am using
below code –
Dim LastCol As Long
Dim rng As Range
Dim rng2 As Range
Dim i As Integer
‘ After the last column with data change the value of the cell in row 1
For i = 1 To 895
rng.Parent.Cells(i, LastCol + 1).Value = rng2.Parent.Cells(i,1j).Value
Next I
With above coe I am able to only copy the first column from Sheet2 where
as I need to copy all columns for sheet2 is the 1st column in sheet2 is same
as 1st column in Sheet1
Can you please help with the actual code
Reply
Good day
How do i get the sheet index number to loop for example
=’1′!$A$1
=’2′!$A$1
=’3′!$A$1
=’4′!$A$1
Reply
Worksheets(1).Range(“$A$1”).Value
Worksheets(2).Range(“$A$1”).Value
Reply
Ira Marvin on October 11, 2017 at 6:53 pm
Great Content.
Reply
Reply
I’m just starting about loops and your site is plentiful of examples,
Congratulations.
Reply
Hi John,
You could write code in the loop to make it happen but would be
very messy.
It is much better practice to use two loops for something like this. It
makes the code clearer
Paul.
Reply
Mireia on March 21, 2018 at 10:30 am
Dear Paul,
I know something about VBA but never used loops. This was great help
thanks!!
*******************************************************
Sub example()
Application.CutCopyMode = False
Sheets(“Sheet2”).Select
Application.GoTo Range(“A1”), True
Application.Run “example.xlsm!example1”
Application.CutCopyMode = False
Application.Run “example.xlsm!example2”
Application.CutCopyMode = False
Application.Run “example.xlsm!example3”
Application.CutCopyMode = False
Sheets(“Sheet2”).Select
Range(“A1”).Select
End Sub
****************************************************************
*******
Could I make this macro have a loop? It is a long dataset, it goes through it
until a change in a cell and then does a lot of stuff. But then I want it to start
again. Could it be possible?
Regards,
Mireia.
Reply
Hi Mireia,
Dim i As Long
For i = 1 To 3
Application.Run "example.xlsm!example" & i
Application.CutCopyMode = False
Next i
Paul
Reply
Austin Gapinski on June 8, 2018 at 2:15 am
Hi Paul,
Thank you for all the great information above!
I have a problem that I am stuggling to figure out. I am looking to update a
scatter plot every x amount of minutes to keep up with some data that is
being exported into the file from another program.
Would a loop be the proper way to do this? Or is there some other function
out there I should be looking in to!
Reply
You can use a loop with the Application.Wait function. This function
will pause to code for a specific amount of time.
Reply
Pankaj Negi on September 11, 2018 at 11:36 am
Sir,
Sub Main()
Dim x As Integer
Sheets(“Entry Sheet”).Select
lastrows = Range(“A2”, Range(“A2”).End(xlDown)).Rows.Count
For x = 2 To lastrows + 1
Cells(x, 1).Copy
Worksheets(“Brokerage”).Range(“D1”).PasteSpecial
Sheets(“Brokerage”).PrintOut
Next
End Sub
Reply
———————————————————————————————————
————————-
Base INSS: 5.200,00 Sal.Familia INSS: 0,00 Base p/ Prev.Propria(*): 0,00
Sal.Fam.Prev.Propria: 0,00
Reply
Hi Benedito,
For example
Paul
Reply
Samim Malikzay on December 13, 2018 at 8:05 am
Hi sir,
I have a question about a for loop in VBA. Could you please help me?
Question:
This (see below) code is part of a code that draws in autocad. According to
the code the program searchs all cells to see if there is a command or value
in de cell. I want to know if there is a way to stop the loop when there is a
specific text in de cell.
I want to tell VBA to stop the Loop when this (\\C:myfolder) text is written in
a cell. I have been looking for a while, if you could take a look at it and help
me it would be wonderful. Thanks in advance!
code:
‘Loop through all the rows of the sheet that contain commands.
For i = 13 To LastRow
‘Create a string that incorporates all the commands that exist in each row.
acadCmd = “”
For j = 3 To LastColumn
If Not IsEmpty(.Cells(i, j).Value) Then
acadCmd = acadCmd & .Cells(i, j).Value & vbCr
End If
Next j
Kind regards,
Samim
Reply
Paul
Reply
Poornachander B on March 19, 2019 at 8:00 am
Dear Paul,
I am new to Macro’s
I have a scenario which I have two tables like below
Date Product Code Selling Price Sales per month Balance in Stock Profit
Amount Loss Amount Profit in % Loss In % Total Amount
Jan 112 255 158 40290
Jan 116 152 99 15048
Feb 118 130 98 12740
Mar 118 131 135 17685
Jan 119 160 100 16000
Feb 112 300 49 14700
Feb 119 150 99 14850
Mar 116 153 143 21879
Mar 112 245 200 49000
Feb 120 150 38 5700
Feb 116 150 200 30000
Jan 118 135 287 38745
and
now I have to Calculate Profit and loss in terms of amount and % using
nested loops
Reply
Jeyner Lopez on June 12, 2019 at 4:16 pm
Hi, thanks for everything. I don’t see nowhere mention a loop to repeat
formulas or application like coefficient trendline and control the x and y, or
looping average, or looping forecasting, it is possible to talk about this.
PLEASE.
THANK YOU SIR.
Reply
Hi Paul,
Thank you for all the great information above. I have a assignment to do on
every month.
There are a set of excel file which need to be consolidated into one
workbook and all are in sheet1. It will be very helpful if you provide your
assistance. i have tired many VBA codes but still not successful. I’m very
new to the VBA.
The below code go to the folder path and update the file name in
destination workbook called as “zmaster” and paste in consolidation sheet.
I don’t want name to be updated what i want is i need the data which is
updated in each input files from column A to P.
Sub folder()
Dim wb As ThisWorkbook
Set wb = ThisWorkbook
Dim ws As Worksheet
Set ws = wb.Worksheets(“consolidation”)
Dim rownum As Integer
rownum = 1
Reply
Hongjie Lin on August 16, 2019 at 6:00 am
For i = 1 To 1000
If KL.Cells(i, 1) = “(Serial No.” Then
Dim rg As Range
Set rg = KL.Cells(i, 1).CurrentRegion
Dim cell As Range
For Each cell In rg
If Val(cell) > 0 Then
count = count + 1
End If
Next cell
Debug.Print count
count = 0
End If
Next i
Reply
Kumar on March 2, 2020 at 5:01 pm
How to Loop in sheet 1 step by 1 and in second sheet step by 2
simultaneously
Thanks
Kumar
Reply
Reply
Reply
Reply
Shijo Xavier on June 19, 2020 at 3:36 am
Hi Paul
My knowledge in VBA is too bad. Just want to have a help from you. I am
trying to run a number of employees in a Row (starting from A2 to the last
cell with the value, no blank cell meanwhile). For some cases, I get error
while running a cell value and I want to skip that error and run with the
next cell.
Currently, I am using the codes
Dim Rng As Range
Set Rng = Range(“A2”,
Range(“A2”).End(xlDown)).Cells.SpecialCells(xlCellTypeVisible)
For Each cell In Rng
my codes here and then
I am aware about the line where I can get an error, so I use the code as
On Error GoTo Errhandler
once I furnished with codes here
Errhandler:
and my codes updated here and then
Exit Sub
and again want to continue with the next cell but it is failed and stopping it
there.
Please help me.
Thanks
Reply
herbet
Reply
Jeyner Lopez on September 9, 2020 at 11:11 pm
Thank you Paul for all the great job you share with Us.
Reply
Reply
Reply
Reply
Paul Kelly on February 6, 2021 at 3:15 am
Hi Mort,
What do you mean by “does not work”? Are you getting an error or
is the result not what you are expecting?
If you step through the code and look at the variables in the watch
window you should be able to see the issue.
-Paul
Reply
Neil on August 28, 2021 at 11:49 pm
Lets say I have a text file like so.
903135
475235
138026
023723
490988
462780
786904
304518
018123
137838
770568
903205
682497
so my last line will look like -3 +8 -1 +2 +9 +2
I want to iterate place all the numbers into an array or I might not have to
and us a
do while !EOF
loop through each column and compare it to the number in the same row
of the next column and write the difference into another text file or another
worksheet, any idea how i could do this?
Reply
You are not logged in
You are not currently logged in.
Username or Email Address:
Password:
Remember Me
Login
» Register
» Lost your Password?
Designed by Elegant Themes | Powered by WordPress