Excel vba stop for

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

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

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

VBA-Break-For-Loop

How to Break/Exit Loops in VBA?

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

#1 – Break For Next Loop

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

Code:

Sub Exit_Loop()

 Dim K As Long

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

End Sub

It will insert serial numbers from cell A1 to A10.

Break For Loop Example 1

It is the obvious thing with For Next Loop.

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

Break For Loop Example 1-1

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

Code:

Sub Exit_Loop()

 Dim K As Long

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

End Sub

Look at these lines of code:

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

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

The last part of the loop says:

Else

  Exit For

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

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

Break For Loop Example 1-2

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

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

Code:

Sub Exit_Loop()

 Dim K As Long

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

End Sub

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

Exit For Next Loop 1-3

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

#2 – Break Do Until Loop

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

Code:

Sub Exit_DoUntil_Loop()

 Dim K As Long
 K = 1

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

End Sub

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

Code:

Sub Exit_DoUntil_Loop()

 Dim K As Long
 K = 1

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

End Sub

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

Code:

Sub Exit_DoUntil_Loop()

 Dim K As Long
 K = 1

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

End Sub

This will show the message below.

Exit Do Until Loop

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

Recommended Articles

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

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

Return to VBA Code Examples

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

Exit For

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

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

Exit a For Loop When a Condition is Met

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

Dim i As Integer

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

MsgBox "The value is " & i

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

For i = 1 To 10

Next i

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

If i = 5 Then

    Exit For

End If

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

Next i

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

MsgBox "The value is " & i

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

vba exit for

Image 1. Exit For Loop example

VBA Coding Made Easy

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

Learn More!

VBA Break for loop

Excel VBA Break For Loop

VBA Break is used when we want to exit or break the continuous loop which has certain fixed criteria. For loop is within the scope range defines the statements which get executed repeatedly for a fixed number of time. Sometimes when we use any loop condition in VBA, it often happens that the code keeps on running without an end or break. To avoid this kind of situations it is recommended to use some breaks or exit functions by which we can exit from the loop with the measurable output from the macro.

How to Use Excel VBA Break For Loop?

We will learn how to use a VBA Break for Loop with few examples in Excel.

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

Example #1 – VBA Break For Loop

We will see an example where when using For loop the criteria arrange will not be broken. But to fix this we will use the If-End loop. For this, we need a Module where we will write this code.

Follow the below steps to use Break for Loop in Excel VBA.

Step 1: Open a new module go to the VBA window and in that select Module from the Insert menu option.

New Module

Step 2: This will take us to a new module in VBA. Now in that module write Subcategory in the name of VBA Break For Loop or in any other name which defines its meaning.

Code:

Sub VBABreak1()

End Sub

Break loop example 1

Step 3: Now define a DIM as any alphabet or word. This gives it an identity. Here we are using the alphabet “A” below.

Code:

Sub VBABreak1()

   Dim A 

End Sub

Break loop example 2

Step 4: Now assign it as Integer which is used for numbers only as shown below.

Code:

Sub VBABreak1()

   Dim A As Integer

End Sub

Break loop example 3

Step 5: Now assign a numeric value to Integer A. Let’s say it is 10 as shown below.

Code:

Sub VBABreak1()

   Dim A As Integer
   A = 10

End Sub

Break loop example 4

Step 6: Now start a For loop and consider any starting value of A. It is better to take this value as Zero. This becomes easy for calculation.

Code:

Sub VBABreak1()

   Dim A As Integer
   A = 10

   For A = 0 To A Step 2

End Sub

Break loop example 5

Step 7: And to print the value stored in A, we will use a message box that will fetch its value. You can use any form of a sentence as well to make the message box more meaningful which is optional. We have used it on as shown below.

Code:

Sub VBABreak1()

   Dim A As Integer
   A = 10

   For A = 0 To A Step 2
     MsgBox ("The value is A is : " & A)
   Next

End Sub

Break loop example 6

Step 8: Now compile the code step-by-step by using functional key F8 and after that run the code by clicking on the Play button as shown below. We will see the output in every step will be from 0 to 10 in the step gap of 2 as shown below.

break vba 1

Step 9: Now at last close For Loop and also use Next at the end. The “Next” is used when we are using numbers in the code.

Code:

Sub VBABreak1()

Dim A As Integer
   A = 10

   For A = 0 To A Step 2
      MsgBox ("The value is A is : " & A)

      Exit For
   Next

End Sub

Break loop example 7

Step 10: This shows that the loop is not complete and we need to fill the exit criteria as well to exit from For loop. And for that, we will use If-End Loop condition. So consider writing If loop for same Integer A. Here choose the limit till you want to run the loop. We have considered it as 4.

Code:

Sub VBABreak1()

Dim A As Integer
   A = 10

   For A = 0 To A Step 2
      MsgBox ("The value is A is : " & A)
   If A = 4 Then

      Exit For
   Next

End Sub

VBA IF condition

Step 11: Now let’s add one more criterion in which we will use how many times it would get multiplied by any number. Let’s say it is 10. You can choose any other number instead of 10. But using 10 makes easy to understand the multiplication loop.

Code:

Sub VBABreak1()

Dim A As Integer
   A = 10

   For A = 0 To A Step 2
      MsgBox ("The value is A is : " & A)
   If A = 4 Then
   A = A * 10

      Exit For
   Next

End Sub

VBA Break

Step 12: Now again use name message box as we have used for For loop and at lastly close the If Loop with End if statement as shown below.

Code:

Sub VBABreak1()

Dim A As Integer
   A = 10

   For A = 0 To A Step 2
      MsgBox ("The value is A is : " & A)
   If A = 4 Then
   A = A * 10
   MsgBox ("The value is A is : " & A)

      Exit For
      End If
   Next

End Sub

MsgBox 2

Step 13: Again compile the code and run it. For Loop will start from showing a message with value 0 and then followed by 2, 4 and ending it 40. Which means For Loop got broken when at 3rd iteration and took the last value as 40.

break vba 2

Example #2 – VBA Break For Loop

In this example, we will apply For loop and will see how to break the loop once it satisfies the criteria.

Step 1: Open a new module from the Insert menu option and give it a Subcategory in any name or better in a sequential manner as shown below.

Code:

Sub VBABreak2()

End Sub

VBA Break loop example 1

Step 2: Now define a DIM A as Integer. Using Integer for test allow us to implement the code faster and debug easy.

Code:

Sub VBABreak2()

  Dim A As Integer

End Sub

Dim Integer

Step 3: Now start a For loop for defined integer and give it a range from any row count starting from 1. We have chosen till 20.

Code:

Sub VBABreak2()

  Dim A As Integer
   For A = 1 To 20

End Sub

For condition

Step 4: Now give a range or location from where the numbers are getting printed in sequence. We used ThisWorkBook to select current opened file and Worksheets(1) for selecting the first sheet of an opened workbook as shown below. Now to close the For loop write Next at the end as shown below.

Code:

Sub VBABreak2()

 Dim A As Integer
  For A = 1 To 20

ThisWorkbook.Worksheets(1).Cells(A, 1) = A

Next

End Sub

Worksheet

Step 5: Run the above code manually or using the shortcut key F5. We can see that the code has given number count from 1 to 20.

Break loop Out

Step 6: Now to break the loop in between from 0 to 20, we will use If-End if loop condition where we will give the criteria to fall in as shown below.

Code:

Sub VBABreak2()

  Dim A As Integer
   For A = 1 To 20

   If

   End If

  ThisWorkbook.Worksheets(1).Cells(A, 1) = A

Next

End Sub

New If End Condition

Step 7: Now write the criteria, If A is greater than 9 (Or any number but less than 20) then Exit For as shown below. We suppose For Loop should get broken when loop reaches 9.

Code:

Sub VBABreak2()

 Dim A As Integer
  For A = 1 To 20

  If A > 9 Then
  Exit For

  End If

 ThisWorkbook.Worksheets(1).Cells(A, 1) = A

Next

End Sub

Exit For

Step 8: Now compile the code to find the error. If no error found then run it. We will see for integer A values from 1 to 20 have been filled till the code exited or broken at position 9.

break vba 3

Pros of VBA Break For Loop

  • Exit or Break can be used not only for For loop but in many other loops as well such as Do-While.
  • This is most frequently used among all the loop conditions available in VBA.
  • For Loop is quite easy and can work even without Exit criteria.

Things to Remember

  • For loop can work without giving the Exit criteria. It can work fine until the criteria without Exit is breaking the loop to end.
  • It is important to Break any loop which doesn’t satisfy the exit criteria by using Exit in the loop.
  • After writing the code, save the file as Macro Enable Excel so that written code will be preserved.

Recommended Articles

This has been a guide to VBA Break For Loop. Here we discuss how to use Excel VBA Break For Loop along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA InStr
  2. VBA Integer
  3. VBA Select Cell
  4. VBA Transpose

How to Exit, End, or Break out of loops in Excel.

This tutorial includes breaking out of While, Do, and For loops.

Sections:

Break out of a Do Loop

Break out of a For Loop

Break out of a While Loop

Break out of a Loop when a Condition is Met

Notes

Break out of a Do Loop

This will exit or break out of a Do loop, including Do While and Do Until loops. When this occurs, script execution will continue after the current loop. If there are Do loops nested within Do loops, only the one directly containing the Exit statement will be broken out of and execution of the script will continue with the next containing Do loop.

Exit Do

Simply put this in the place where you want to exit the loop.

Break out of a For Loop

This will exit or break out of a For loop, which includes a For…Next loop and a For Each…Next loop. When this occurs, script execution will continue after the current loop. If there are nested For loops, only the one directly containing the Exit statement will be broken out of and execution of the script will continue with the next containing For loop.

Exit For

Simply put this in the place where you want to exit the loop.

Break out of a While Loop

This will exit or break out of a While loop. When this occurs, script execution will continue after the current loop. If there are While loops nested within While loops, only the one directly containing the Exit statement will be broken out of and execution of the script will continue with the next containing While loop.

Exit While

Simply put this in the place where you want to exit the loop.

Break out of a Loop when a Condition is Met

Now you know the simple syntax for exiting a loop, but it’s not useful without a condition.

Include the Exit statement within an IF condition. Use the IF condition to check if it is time to exit from the loop or not.

Here is a very basic loop example along with a condition that checks from when the loop needs to be canceled or exited.

Sub Loop_Death()

For i = 1 To 10

    'show some output
    MsgBox i

    If i = 5 Then

        'exit the loop
        Exit For

    End If

Next i

End Sub

Here it is in Excel for better reference:

3400f030ce7363c7e00549c99c10b8af.jpg

Here, I made a simple For loop that should run 10 times. However, I placed an IF statement that checks when the variable i has reached 5 and, when this happens, the Exit For line of code will run and the For loop will be broken out of or exited and, since there is no other loop containing this loop or any code after the loop, there is nothing else for the macro to do and so its execution will end.

I included a msgbox output that will display the value contained within the variable i, which will just be the number of times the loop has run since that variable is incremented each time the loop runs. This feature is there just to help you visualize the exit from the For loop.

You can also use a one-line IF statement like this to streamline the code:

Sub Loop_Death()

For i = 1 To 10

    'show some output
    MsgBox i

    If i = 5 Then Exit For

Next i

End Sub

938fd637564a37da7fba562401a712e7.jpg

Notes

This is a basic feature of VBA and Macros but it is very important and it will help you add a lot of control to your macros. Make sure to memorize these three simple Exit statements for the loops.

There is no Exit statement for a While Wend loop. If you need to exit one of these loops, simply change it to a Do While or Do Until loop.

Don’t forget to download the Excel file that accompanies this tutorial and test this macro out.

Similar Content on TeachExcel

Loop through a Range of Cells in a UDF in Excel

Tutorial:
How to loop through a range of cells in a UDF, User Defined Function, in Excel. This is …

Loop through a Range of Cells in Excel VBA/Macros

Tutorial: How to use VBA/Macros to iterate through each cell in a range, either a row, a column, or …

Highlight, Sort, and Group the Top and Bottom Performers in a List in Excel

Tutorial:
How to highlight the rows of the top and bottom performers in a list of data.
This allows…

5 Simple Tips for Making BETTER Macros in Excel!

Tutorial:
5 ways to make better Macros in Excel — fewer errors, smoother coding, less fuss!
These 5…

Sort Data With Headers in Ascending Order in Excel

Macro: Macro that sorts data that has headers in ascending order in Excel. This macro assumes tha…

Create a Column Chart with a Macro in Excel

Macro: This macro adds a column chart to Excel. This is an easy to use macro that allows you to q…

Subscribe for Weekly Tutorials

BONUS: subscribe now to download our Top Tutorials Ebook!


A Exit For statement is used when we want to exit the For Loop based on certain criteria. When Exit For is executed, the control jumps to the next statement immediately after the For Loop.

Syntax

Following is the syntax for Exit For Statement in VBA.

 Exit For

Flow Diagram

VBA Exit For statement

Example

The following example uses Exit For. If the value of the Counter reaches 4, the For Loop is exited and the control jumps to the next statement immediately after the For Loop.

Private Sub Constant_demo_Click()
   Dim a As Integer
   a = 10
   
   For i = 0 To a Step 2 'i is the counter variable and it is incremented by 2
      MsgBox ("The value is i is : " & i)
      If i = 4 Then
         i = i * 10 'This is executed only if i=4
         MsgBox ("The value is i is : " & i)
         Exit For 'Exited when i=4
      End If
   Next
End Sub

When the above code is executed, it prints the following output in a message Box.

The value is i is : 0

The value is i is : 2

The value is i is : 4

The value is i is : 40 

vba_loops.htm

Понравилась статья? Поделить с друзьями:
  • Excel vba split несколько разделителей
  • Excel vba split for
  • Excel vba spinbutton textbox
  • Excel vba source control
  • Excel vba sorting function