Break for loop excel

I would like to exit my for loop when a condition inside is met. How could I exit my for loop when the if condition has been met? I think some kind of exit at the end of my if statement, but don’t know how that would work.

Dim i As Long
For i = 1 To 50
    Range("B" & i).Select
    If Range("B" & i).Value = "Artikel" Then
        Dim temp As Long
        temp = i
    End If
Next i
Range("A1:Z" & temp - 1).EntireRow.Delete Shift:=xlToLeft

Dragonthoughts's user avatar

asked Feb 23, 2012 at 14:29

CustomX's user avatar

1

To exit your loop early you can use Exit For

If [condition] Then Exit For

answered Feb 23, 2012 at 14:39

Dan's user avatar

DanDan

5,0711 gold badge18 silver badges28 bronze badges

2

Another way to exit a For loop early is by changing the loop counter:

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

Debug.Print i   '11

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

Debug.Print i   '5

answered Oct 10, 2015 at 23:17

paul bica's user avatar

paul bicapaul bica

10.5k4 gold badges22 silver badges41 bronze badges

2

The first answer given with the following is indeed i.m.o. best practice:

if i = 0 then exit for

However, this is also an option:

Sub some()

Count = 0
End_ = ThisWorkbook.Sheets(1).Range("B1047854").End(xlUp).Row

While Count < End_ And Not ThisWorkbook.Sheets(1).Range("B" & Count).Value = "Artikel"
    Count = Count + 1
    If ThisWorkbook.Sheets(1).Range("B" & Count).Value = "Artikel" Then
        ThisWorkbook.Sheets(1).Range("A1:Z" & Count - 1).EntireRow.Delete Shift:=xlToLeft
    End If
Wend

End Sub

answered Feb 29, 2020 at 10:59

ko_00's user avatar

ko_00ko_00

1187 bronze badges

if condition (inside your while — loop) then goto (some marker outside the loop)

answered Apr 19, 2022 at 5:45

user18858896's user avatar

1

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

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!

What is break statement generally?

In programming languages, there is normally a break statement available to exit a loop (For loop, While, Do While) while it is still not completed.

There is no break keyword/statement in VBA.

Using the Exit For

In VBA, we use Exit For to get out of the for loop entirely.

We will show you simple as well as exiting for loop in the array below.

How to exit a for loop in VBA?

In this example,

  • we set a variable initial value to 1.
  • A for loop is used to iterate till value of variable i = 10
  • In each iteration, the value of i increases by 1.
  • We will concatenate the current value of i, and as for loop finishes, a MsgBox is displayed as shown below:

Normal for loop without breaking it:

Sub for_exit()

Dim i As Integer

Dim curr

For i = 1 To 10 Step 1

curr = curr & vbNewLine & i

Next i

MsgBox curr

End Sub

Output:

VBA-for-loop-normal

Break the for loop by Exit For

The example below exits the For loop by using “Exit For” as the value of i reaches 5:

VBA code:

Sub for_exit()

Dim i As Integer

Dim curr

For i = 1 To 10 Step 1

If i >= 5 Then

Exit For

Else

    curr = curr & vbNewLine & i

End If

Next i

MsgBox curr

End Sub

Output:

VBA-for-loop-exit

You can see, For loop till the value of i reached 5.

Exiting an array with For Each loop example

Similarly, you may exit the For..Each loop that we use with arrays or collections.

In the example below, we have a string array of four elements. As we reach the third item, we will check its value and exit the For..Each loop.

First, let us show how it works without Exit For:

The code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

Sub for_exit()

Dim Prog_Langs(1 To 4) As String

Dim combined_str As String

Dim arr_item As Variant

‘Array Elements

Prog_Langs(1) = «C#»

Prog_Langs(2) = «Go Lang»

Prog_Langs(3) = «C++»

Prog_Langs(4) = «Python»

‘Using the For Next loop

For Each arr_item In Prog_Langs

combined_str = combined_str & arr_item & «, «

Next arr_item

‘Display all array elements

MsgBox combined_str

End Sub

Output:

VBA-for-each

Now, we will exit the For..Each loop as it encountered the array element “C++”. So, MsgBox should display only two languages:

Code with “Exit For”:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

Sub for_exit()

Dim Prog_Langs(1 To 4) As String

Dim combined_str As String

Dim arr_item As Variant

‘Array Elements

Prog_Langs(1) = «C#»

Prog_Langs(2) = «Go Lang»

Prog_Langs(3) = «C++»

Prog_Langs(4) = «Python»

‘Using the For Next loop with Exit For

For Each arr_item In Prog_Langs

If arr_item = «C++» Then

Exit For

End If

combined_str = combined_str & arr_item & «, «

Next arr_item

‘Display array elements

MsgBox combined_str

End Sub

Result:

VBA-for-each-Exit

Понравилась статья? Поделить с друзьями:
  • Break broken links excel
  • Break all links word
  • Break all links in excel
  • Break a word in latex
  • Bread loaf in one word