How to use the FOR NEXT statement
Table of Contents
1. FOR NEXT Syntax
For counter = start To end Step step
... statements ...
[ Exit For ]
... statements ...
Next [ counter ]
counter is a variable
start, end, and step are numbers
2. FOR NEXT with a counter variable
You can have a variable that counts for you, in this case, it is variable i. The FOR NEXT statement runs the lines between FOR and NEXT ten times incrementing variable i with 1 each time. See picture above.
It starts with 1 and continues up to 10. 1+2+3+4+5+6+7+8+9+10 = 55. It is not necessary to include the variable name after the NEXT statement, however, it will be easier to read your code if you do so.
The message box then displays the sum. As soon as you press with left mouse button on the OK button the macro ends.
'Name macro Sub Macro1() 'For Next statement For i = 1 to 10 'Add number stored in variable i to variable Result Result = Result + i 'Continue with next number Next i 'Display message box containing number stored in variable Result MsgBox Result 'Exit macro End Sub
3. FOR each NEXT example
The picture above demonstrates a FOR NEXT statement that goes through each cell value in cell range B3:B8 and adds it to a total.
The Message box then displays the sum. 4+2+5+3+6+4 is 24. Here is the subroutine:
'Name macro Sub Macro1() 'For each Next statement For Each Value In Range("B3:B8") 'Add value to variable Result Result = Result + Value 'Continue with next value in cell range Next Value 'Display message box containing number in variable result MsgBox Result 'Exit macro End Sub
The Value variable stores the number from cell B3 in the first iteration then continues to B4 and overwrites the previous value, and so on. The Result variable adds each value in every iteration and builds a sum.
The macro repeats the lines between FOR and NEXT as many times as there are cells in Range("B3:B8).
The message box displays the sum and you then need to press with left mouse button on the OK button to proceed.
4. FOR NEXT with counter variable and STEP keyword
The STEP keyword allows you to increase or decrease the counter value with a number you specify.
If you use a negative step number make sure the end counter number is less than the start counter number to avoid your macro being in an endless loop.
In the above example, the counter variable is i and it starts with 10 and ends with 1, the STEP value is -2. 10+8+6+4+2=30.
'Name macro Sub Macro1() 'For each Next statement For i = 10 To 1 Step -2 'Add value to variable Result Result = Result + i 'Continue with next value in cell range Next i 'Display message box containing number in variable result MsgBox Result 'Exit macro End Sub
5. FOR NEXT and EXIT FOR statements
The EXIT FOR statement allows you to stop iterating through a FOR NEXT statement which is handy if, for example, an error value shows up.
The picture above uses the IF THENÂ statement to check if counter variable i is equal to 6. 10 + 8 + 6 = 24.
'Name macro Sub Macro1() 'For each Next statement For i = 10 To 1 Step -2 'Add value to variable Result Result = Result + i 'Check if variable i equals 6 and Exit For Next statement if true If i = 6 then Exit For 'Continue with next value in cell range Next i 'Display message box containing number in variable result MsgBox Result 'Exit macro End Sub
6. FOR each NEXT - array values
The code below demonstrates a FOR NEXT statement that goes through each value in an array variable.
The Message box then displays each array value on a new line. Here is the subroutine:
'Name macro Sub Macro1() 'Save values to an array variable arr = Array("Blue", "Yellow", "White") 'For each Next statement For i = LBound(arr) To UBound(arr) 'Concatenate array value to variable txt and a new line res = res & arr(i) & vbNewLine 'Continue with next value in array Next i 'Display message box containing number in variable res MsgBox res 'Exit macro End Sub
Get Excel *.xlsx file
How to use the FOR NEXT statement.xlsm
FOR examples
Table of Contents Add Checkboxes to a Worksheet Copy selected rows based on check boxes Worksheet data VBA code Where […]
In this tutorial, I am going to show you how to add values to a drop down list programmatically in […]
This article demonstrates two ways to calculate the number of times each word appears in a given range of cells. […]
This article demonstrates how to automatically create drop-down lists if adjacent data grows, there are two methods explained here. The […]
Excel does not resize columns as you type by default as the image above demonstrates. You can easily resize all […]
This article demonstrates how to automatically enter data in cells if an adjacent cell is populated using VBA code. In […]
This article demonstrates how to convert a range of cells containing strings separated by a delimiter into a range of […]
In this article I will demonstrate how to quickly change chart data range utilizing a combobox (drop-down list). The above […]
The image above shows a chart populated with data from an Excel defined Table. The worksheet contains event code that […]
In this article, I am going to show you how to quickly change Pivot Table data source using a drop-down […]
What's on this page Press with left mouse button on a specific cell to hide/show entire column Where to put […]
The image above demonstrates a user defined function that merges up to 255 cell ranges and removes blanks. I will also […]
Today I would like to share a macro that compares the content in two different folders and their subfolders. It […]
Question: I have multiple worksheets in a workbook. Each worksheets is project specific. Each worksheet contains almost identical format. The […]
I will in this article demonstrate a macro that automatically opens all workbooks in a folder and subfolders, one by […]
I will in this article demonstrate a macro that copies criteria from one Excel Table and applies them to another […]
This article demonstrates a macro that copies selected rows based on enabled check boxes. The image above shows data on […]
This article demonstrates several VBA macros, they will save you time if you have lots of worksheets. The first macro […]
This article demonstrates a User Defined Function (UDF) that counts how many times a string exists in a cell value […]
I will in this article demonstrate a macro that counts how many times a specific text string is found in […]
This article demonstrates a User Defined Function (UDF) that counts unique distinct cell values based on a given cell color. […]
This article describes how to count unique distinct values in list. What is a unique distinct list? Merge all duplicates to one […]
This article describes how to create a button and place it on an Excel worksheet, then assign a macro to […]
It can sometimes be helpful having a large cell value in a comment. You can then easily hover over cell […]
The macro demonstrated above creates hyperlinks to all worksheets in the current worksheet. You will then be able to quickly […]
This article demonstrates a macro that inserts new worksheets based on names in a cell range. The cell range may […]
Terry wants to make a different sized maze and I think that is a great idea. Perhaps you remember that I […]
In a previos post:Excel vba: Save invoice data we added/copied data between sheets. This post describes how to overwrite existing […]
In this article, I am going to demonstrate a simple workbook where you can create or delete projects and add […]
Table of Contents Functions How to use the ARRAY function How to use the FIX function How to use the […]
This article demonstrates a User Defined Function that allows you to extract cell references from a formula in a given […]
This article demonstrates a macro that returns cell references for cell ranges populated with values on a worksheet. Jinesh asks: […]
Blake asks: I have a somewhat related question, if you don't mind: I have very large amount of text in […]
This article demonstrates two formulas that extract distinct values from a filtered Excel Table, one formula for Excel 365 subscribers […]
Picture above shows cheap chinese IoT modules: a temp sensor and an esp8266-01 (25 mm x 15 mm) Thingspeak […]
In this post I am going to demonstrate how to quickly apply a filter to a table. I am using […]
This is a follow up to my last post Compare file names in two different folder locations and their subfolders, the obvious […]
AJ Serrano asks: I have a column where each rows contains different values and I wanted to obtain the duplicate […]
This article demonstrates a user defined function that extracts duplicate values and also count duplicates. Example, the image below shows a list containing […]
This post describes a custom function (User defined Function) that extract values existing only in one out of two cell […]
The User Defined Function demonstrated in the above picture extracts unique distinct values also considering lower and upper case letters. […]
This blog post describes how to create a list of unique distinct words from a cell range. Unique distinct words […]
This blog post describes how to create a list of unique words from a cell range. Unique words are all […]
I tried the array formula in this post: Filter common values between two ranges using array formula in excel to […]
The following two macros FindReplace() and Recursive() let you rename files and folders recursively based on a search string. The […]
This article describes different ways to locate literal or hardcoded values in formulas. The image above shows the result from […]
This article describes how to find a sum from a range of numbers using a user defined function. Let´s see […]
Question:I would like to reduce the number of open items by identifying positive and negative amounts that net to zero […]
This post Find the longest/smallest consecutive sequence of a value has a few really big array formulas. Today I would like to […]
What's on this page Finding the shortest path - A * pathfinding Optimize pick path in a warehouse 1. […]
This article describes a macro that hides specific columns automatically based on values in two given cells. I am also […]
This article demonstrates techniques to hide and unhide worksheets programmatically. The image above shows the Excel window and the worksheet […]
This post describes how to add a new custom-built item to the shortcut menu in Excel, when you press with right […]
This article demonstrates a formula and a VBA macro that returns every n-th row from a given cell range. The […]
The image above demonstrates a macro linked to a button. Press with left mouse button on the button and the […]
If you try to copy multiple cell ranges on a worksheet that don't have the same number of rows or […]
This article demonstrates formulas that count values in cell based on a delimiting character. The image above shows a formula […]
Did you know that you can select all cells containing comments in the current sheet? Press F5, press with left […]
This article describes how to create an interactive chart, the user may press with left mouse button on a button […]
Today I would like to share with you these small event handler procedures that make it easier for you to […]
This article demonstrates how to automatically create log entries when a workbook opens or closes using event code. Column A […]
This article demonstrates macros that save worksheets to a single pdf file. What's on this webpage Export all worksheets in […]
A dialog box is an excellent alternative to a userform, they are built-in to VBA and can save you time […]
The ARRAY function creates a Variant variable containing array values. Table of Contents Array Function VBA Syntax Array Function Arguments […]
The FIX function removes the decimals from the argument. Excel Function VBA Syntax Fix(number) Arguments number Required. Is a Double or […]
Table of Contents FOR NEXT statement FOR NEXT with a counter variable FOR each NEXT example FOR NEXT with counter […]
The INT function removes the decimals if the numeric value is above 0 (zero) and returns a negative integer less than […]
The LIKE operator allows you to match a string to a pattern using Excel VBA. The image above demonstrates a […]
This article demonstrates how to insert and use a scroll bar (Form Control) in Excel. It allows the user to […]
The SGN function returns an integer that shows the sign of the number. Argument SGN returns Number greater than 0 (zero). […]
The picture above shows a user-defined function (UDF) that splits the string in cell C3 using a delimiting character ",". […]
The image above shows an array formula in cell D6 that extracts missing numbers i cell range B3:B7, the lower […]
In this vba tutorial I am going to show you how to return values from an udf, depending on where […]
The macro in this blog post lists all hyperlinks in a worksheet. It also lists all words beginning with "http" […]
In this post, I am going to demonstrate how to automatically create a new sheet in the current workbook and […]
The following macro inserts a new sheet to your workbook and lists all Excel defined Tables and corresponding Table headers […]
This article demonstrates a user defined function that lists files in a ggiven folder and subfolders. A user defined function is […]
This blog post describes how to create permutations, repetition is NOT allowed. Permutations are items arranged in a given order meaning […]
This blog post demonstrates a custom function (UDF) that creates permutations. Repetition is allowed. The custom function lets you specify the […]
This article demonstrates how to locate a shape in Excel programmatically based on the value stored in the shape. The […]
This article explains how to perform multiple lookups based on values in one cell with a delimiting character using a […]
Today I will share a To-do list excel template with you. You can add text to the sheet and an […]
This article demonstrates a recursive LAMBDA function and a User Defined Function (UDF) that multiplies numbers in each row with […]
To be able to use a Pivot Table the source data you have must be arranged in way that a […]
This tutorial shows you how to list excel files in a specific folder and create adjacent checkboxes, using VBA. The […]
In this tutorial I am going to explain how to: Create a combo box (form control) Filter unique values and […]
In this post I am going to demonstrate two things: How to populate a combobox based on column headers from […]
Excel defined Tables, introduced in Excel 2007, sort, filter and organize data any way you like. You can also format […]
This post demonstrates how to: Insert a button to your worksheet Assign a macro to the button Create a basic […]
This article demonstrates a macro that allows you to rearrange and distribute concatenated values across multiple rows in order to […]
This article demonstrates different techniques on how to take a screenshot of your worksheet. You can do that by simply […]
Sean asks: Sheet1A B C D 8 Country Europe 9 Lights 100 10 Type A 200 11 12 Country USA […]
Have you ever wondered how these lines got there on a worksheet? They are called "print preview lines" and they […]
The User Defined Function (UDF) demonstrated in this article, resizes a given range to columns or rows you specify. This […]
This article demonstrates how to run a VBA macro using a Drop Down list. The Drop Down list contains two […]
Table of contents Save invoice data - VBA Invoice template with dependent drop down lists 1. Save invoice data - […]
Today I'll show you how to search all Excel workbooks with file extensions xls, xlsx and xlsm in a given folder for a […]
This article demonstrates macros that allow you to search for a text string(s) in multiple worksheets and workbooks located in […]
The image above demonstrates a user-defined function in cell range B6:D7 that allows you to search a folder and subfolders […]
This article demonstrates a macro that automatically applies a filter to an Excel defined Table based on the result from […]
This post demonstrates how to view saved invoices based on the invoice number using a userform. The userform appears when the […]
This post demonstrates a macro that automatically selects cell A1 on each sheet right before you close a workbook. The […]
This article demonstrates a macro and a formula that allows you to sort delimited data in a cell or cell […]
This article demonstrates how to sort a specific column in an Excel defined Table based on event code. The event […]
In this post I am going to show how to create a new sheet for each airplane using vba. The […]
This article demonstrates formulas and a UDF that searches for values in a table based on concatenated values and returns […]
Table of Contents Split values equally into groups Rearrange values based on category - VBA 1. Split values equally […]
The SUBSTITUTE and REPLACE functions can only handle one string, this article demonstrates two ways to handle more than one […]
This post describes two ways to a search multiple ranges and calculate a total of the corresponding values across worksheets […]
This article describes two ways to perform lookups in multiple in multiple cross reference tables simultaneously. The first one being […]
The VBA macro demonstrated in this article lets you unzip all zip files in a folder to a destination folder […]
This blog post describes how to insert qualifers to make "text to columns" conversion easier. Example I copied a table from […]
This article explains how to check if Excel files in a given folder are password protected. The image above shows […]
This post will teach you how to work with Excel arrays in visual basic for applications (VBA). Why do you […]
This blog post demonstrates how to create, populate and change comboboxes (form control) programmatically. Form controls are not as flexible […]
In this blog article, I will demonstrate basic file copying techniques using VBA (Visual Basic for Applications). I will also […]
This blog post shows you how to manipulate List Boxes (form controls) manually and with VBA code. The list box […]
There are two different kinds of text boxes, Form controls and ActiveX Controls. Form controls can only be used on […]
FOR EACH examples
Table of Contents Add Checkboxes to a Worksheet Copy selected rows based on check boxes Worksheet data VBA code Where […]
In this tutorial, I am going to show you how to add values to a drop down list programmatically in […]
This article demonstrates two ways to calculate the number of times each word appears in a given range of cells. […]
This article demonstrates how to automatically create drop-down lists if adjacent data grows, there are two methods explained here. The […]
Excel does not resize columns as you type by default as the image above demonstrates. You can easily resize all […]
This article demonstrates how to automatically enter data in cells if an adjacent cell is populated using VBA code. In […]
The image above shows a chart populated with data from an Excel defined Table. The worksheet contains event code that […]
What's on this page Press with left mouse button on a specific cell to hide/show entire column Where to put […]
The image above demonstrates a user defined function that merges up to 255 cell ranges and removes blanks. I will also […]
Today I would like to share a macro that compares the content in two different folders and their subfolders. It […]
Question: I have multiple worksheets in a workbook. Each worksheets is project specific. Each worksheet contains almost identical format. The […]
I will in this article demonstrate a macro that automatically opens all workbooks in a folder and subfolders, one by […]
I will in this article demonstrate a macro that copies criteria from one Excel Table and applies them to another […]
This article demonstrates a macro that copies selected rows based on enabled check boxes. The image above shows data on […]
This article demonstrates several VBA macros, they will save you time if you have lots of worksheets. The first macro […]
I will in this article demonstrate a macro that counts how many times a specific text string is found in […]
This article demonstrates a User Defined Function (UDF) that counts unique distinct cell values based on a given cell color. […]
This article describes how to count unique distinct values in list. What is a unique distinct list? Merge all duplicates to one […]
It can sometimes be helpful having a large cell value in a comment. You can then easily hover over cell […]
The macro demonstrated above creates hyperlinks to all worksheets in the current worksheet. You will then be able to quickly […]
This article demonstrates a macro that inserts new worksheets based on names in a cell range. The cell range may […]
Table of Contents Functions How to use the ARRAY function How to use the FIX function How to use the […]
This article demonstrates a macro that returns cell references for cell ranges populated with values on a worksheet. Jinesh asks: […]
This article demonstrates two formulas that extract distinct values from a filtered Excel Table, one formula for Excel 365 subscribers […]
In this post I am going to demonstrate how to quickly apply a filter to a table. I am using […]
This is a follow up to my last post Compare file names in two different folder locations and their subfolders, the obvious […]
This article demonstrates a user defined function that extracts duplicate values and also count duplicates. Example, the image below shows a list containing […]
This post describes a custom function (User defined Function) that extract values existing only in one out of two cell […]
The User Defined Function demonstrated in the above picture extracts unique distinct values also considering lower and upper case letters. […]
I tried the array formula in this post: Filter common values between two ranges using array formula in excel to […]
The following two macros FindReplace() and Recursive() let you rename files and folders recursively based on a search string. The […]
This article describes different ways to locate literal or hardcoded values in formulas. The image above shows the result from […]
This article describes a macro that hides specific columns automatically based on values in two given cells. I am also […]
This article demonstrates techniques to hide and unhide worksheets programmatically. The image above shows the Excel window and the worksheet […]
This post describes how to add a new custom-built item to the shortcut menu in Excel, when you press with right […]
The image above demonstrates a macro linked to a button. Press with left mouse button on the button and the […]
If you try to copy multiple cell ranges on a worksheet that don't have the same number of rows or […]
This article demonstrates formulas that count values in cell based on a delimiting character. The image above shows a formula […]
Did you know that you can select all cells containing comments in the current sheet? Press F5, press with left […]
Today I would like to share with you these small event handler procedures that make it easier for you to […]
This article demonstrates macros that save worksheets to a single pdf file. What's on this webpage Export all worksheets in […]
The FIX function removes the decimals from the argument. Excel Function VBA Syntax Fix(number) Arguments number Required. Is a Double or […]
Table of Contents FOR NEXT statement FOR NEXT with a counter variable FOR each NEXT example FOR NEXT with counter […]
The INT function removes the decimals if the numeric value is above 0 (zero) and returns a negative integer less than […]
The LIKE operator allows you to match a string to a pattern using Excel VBA. The image above demonstrates a […]
The SGN function returns an integer that shows the sign of the number. Argument SGN returns Number greater than 0 (zero). […]
The picture above shows a user-defined function (UDF) that splits the string in cell C3 using a delimiting character ",". […]
In this vba tutorial I am going to show you how to return values from an udf, depending on where […]
The macro in this blog post lists all hyperlinks in a worksheet. It also lists all words beginning with "http" […]
The following macro inserts a new sheet to your workbook and lists all Excel defined Tables and corresponding Table headers […]
This article demonstrates a user defined function that lists files in a ggiven folder and subfolders. A user defined function is […]
This article demonstrates how to locate a shape in Excel programmatically based on the value stored in the shape. The […]
This article explains how to perform multiple lookups based on values in one cell with a delimiting character using a […]
Today I will share a To-do list excel template with you. You can add text to the sheet and an […]
This tutorial shows you how to list excel files in a specific folder and create adjacent checkboxes, using VBA. The […]
In this tutorial I am going to explain how to: Create a combo box (form control) Filter unique values and […]
In this post I am going to demonstrate two things: How to populate a combobox based on column headers from […]
Excel defined Tables, introduced in Excel 2007, sort, filter and organize data any way you like. You can also format […]
This post demonstrates how to: Insert a button to your worksheet Assign a macro to the button Create a basic […]
Have you ever wondered how these lines got there on a worksheet? They are called "print preview lines" and they […]
The User Defined Function (UDF) demonstrated in this article, resizes a given range to columns or rows you specify. This […]
Today I'll show you how to search all Excel workbooks with file extensions xls, xlsx and xlsm in a given folder for a […]
This article demonstrates macros that allow you to search for a text string(s) in multiple worksheets and workbooks located in […]
The image above demonstrates a user-defined function in cell range B6:D7 that allows you to search a folder and subfolders […]
This post demonstrates a macro that automatically selects cell A1 on each sheet right before you close a workbook. The […]
This article demonstrates a macro and a formula that allows you to sort delimited data in a cell or cell […]
In this post I am going to show how to create a new sheet for each airplane using vba. The […]
This article demonstrates formulas and a UDF that searches for values in a table based on concatenated values and returns […]
This post describes two ways to a search multiple ranges and calculate a total of the corresponding values across worksheets […]
The VBA macro demonstrated in this article lets you unzip all zip files in a folder to a destination folder […]
This article explains how to check if Excel files in a given folder are password protected. The image above shows […]
In this blog article, I will demonstrate basic file copying techniques using VBA (Visual Basic for Applications). I will also […]
This blog post shows you how to manipulate List Boxes (form controls) manually and with VBA code. The list box […]
EXIT FOR examples
Table of Contents Add Checkboxes to a Worksheet Copy selected rows based on check boxes Worksheet data VBA code Where […]
This article demonstrates two ways to calculate the number of times each word appears in a given range of cells. […]
Today I would like to share a macro that compares the content in two different folders and their subfolders. It […]
This article demonstrates a macro that copies selected rows based on enabled check boxes. The image above shows data on […]
The User Defined Function demonstrated in the above picture extracts unique distinct values also considering lower and upper case letters. […]
What's on this page Finding the shortest path - A * pathfinding Optimize pick path in a warehouse 1. […]
A dialog box is an excellent alternative to a userform, they are built-in to VBA and can save you time […]
Table of Contents FOR NEXT statement FOR NEXT with a counter variable FOR each NEXT example FOR NEXT with counter […]
This blog post describes how to create permutations, repetition is NOT allowed. Permutations are items arranged in a given order meaning […]
Today I will share a To-do list excel template with you. You can add text to the sheet and an […]
This tutorial shows you how to list excel files in a specific folder and create adjacent checkboxes, using VBA. The […]
In this post I am going to demonstrate two things: How to populate a combobox based on column headers from […]
This blog post describes how to insert qualifers to make "text to columns" conversion easier. Example I copied a table from […]
This post will teach you how to work with Excel arrays in visual basic for applications (VBA). Why do you […]
For next statement category
The image above demonstrates a user defined function that merges up to 255 cell ranges and removes blanks. I will also […]
The macro demonstrated above creates hyperlinks to all worksheets in the current worksheet. You will then be able to quickly […]
What's on this page Finding the shortest path - A * pathfinding Optimize pick path in a warehouse 1. […]
How to comment
How to add a formula to your comment
<code>Insert your formula here.</code>
Convert less than and larger than signs
Use html character entities instead of less than and larger than signs.
< becomes < and > becomes >
How to add VBA code to your comment
[vb 1="vbnet" language=","]
Put your VBA code here.
[/vb]
How to add a picture to your comment:
Upload picture to postimage.org or imgur
Paste image link to your comment.
Contact Oscar
You can contact me through this contact form