How to achieve Continue Statement Purpose in VBA?
As we know, VBA has “Exit For”, and “Exit Do” to come out of the loop entirely – which is achieved by the break statement (normally in other programming languages).
However, VBA has no Continue statement – to omit an iteration in the loop rather completely exiting the loop.
So, how we can achieve this? The topic of our tutorial.
First Solution – Using an If statement in the For loop
Generally, the continue statement is placed inside the for loop (in any language where it is available).
We are also using VBA If statement and testing the current value.
See how we will omit the current iteration while the loop still goes on until the condition is False.
VBA omit an iteration code:
Sub for_continue() Dim x As Integer Dim curr_val For x = 1 To 10 Step 1 If x = 4 Then ‘Do Nothing Else curr_val = curr_val & vbNewLine & x End If Next x MsgBox curr_val End Sub |
Output:
You can see, 4 is not displayed in the MsgBox.
If we have not used the If..Else in the above example, the output should be:
Omitting multiple iterations
Just add more items by using Or operator in the If Statement and you may omit more iterations. For example, we will omit 3, 5, and 7 values in our above example. See the code and output below:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Sub for_continue() Dim x As Integer Dim curr_val For x = 1 To 10 Step 1 ‘Omit multiple iterations If x = 3 Or x = 5 Or x = 7 Then ‘Do Nothing Else curr_val = curr_val & vbNewLine & x End If Next x MsgBox curr_val End Sub |
Output:
VBA “Continue” with Array example
Similarly, you may omit the iteration(s) as working with For..Each and arrays.
In the example below, we have five array elements. The array contains fruits’ names. Normally, it will display the array elements as below:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
Sub for_continue() Dim Fruits(1 To 5) As String Dim concat_str As String Dim curr_item As Variant ‘Array Elements Fruits(1) = «Apple» Fruits(2) = «Mango» Fruits(3) = «Banana» Fruits(4) = «Peach» Fruits(5) = «strawberry» ‘Omit values like continue does For Each curr_item In Fruits concat_str = concat_str & curr_item & «, « Next curr_item MsgBox concat_str End Sub |
Output:
To demonstrate “Continue”, we will omit two fruit names by using If..Else statements:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
Sub for_continue() Dim Fruits(1 To 5) As String Dim concat_str As String Dim curr_item As Variant ‘Array Elements Fruits(1) = «Apple» Fruits(2) = «Mango» Fruits(3) = «Banana» Fruits(4) = «Peach» Fruits(5) = «strawberry» ‘Omit values like continue does For Each curr_item In Fruits If curr_item = «Apple» Or curr_item = «Peach» Then ‘Do Nothing Else concat_str = concat_str & curr_item & «, « End If Next curr_item MsgBox concat_str End Sub |
Output:
You can see, the two fruit names are not displayed in the message box.
Loops in VBA
Loops are an essential part of any programming language because they help with the repeated running of any code snippet. Just like any other language, VBA offers the following loops to enable efficient programming:
- Do until
- Do while
- For
- Foreach
In this article we will dive dep into the “for” loop which iterates only for “x” number of times where “x” is a known value before the loop’s runtime.
“X” can also be a predictable number at runtime, for example when you determine the Lbound and Ubound values of arrays.
The For Loop in VBA
In VBA, “for loop” is easy to use. It follows a simple and understandable syntax.
Syntax:
For <counter> = <start> to <end> [ <step value> ]
[ <code block to execute> ]
Next [ <counter> ]
where
<counter>
is the iterator variable which keeps incrementing by the <step value>
after every iteration.
<step value>
is optional. If this value is not provided, the default incremental value is “1.”
<Code block to execute>
is also optional. It is the snippet of code to be executed during every iteration.
The “Next” statement marks the end of the “for” loop. It indicates to move to the next iteration of this loop with the incremented counter value.
Simple Examples of a For Loop
Print a Mathematical Table for a Number
Sub forloop_demo() ' declare all the required variables Dim counter, input_number As Integer ' Receive input from user input_number = InputBox(" Which tables do you want to print ? ") ' Print the mathematical table of the input number upto 12 count For counter = 1 To 12 Debug.Print (counter &amp;amp; " X " &amp;amp; input_number &amp;amp; " = " &amp;amp; counter * input_number) Next End Sub
This program receives a number as an input from the user. Then, using a “for” loop, it is multiplied with each number from 1 to 12 to print a “times table” table of that input number.
A sample output of this program if “3” is input by the user is seen in the image below.
Program to Print Contents of an Array
This program defines an array with its size. All elements of the array are assigned values one by one. Next they are printed as we iterate through a loop. It is noteworthy to say that the iterator variable (i) of the “for” loop is also used as the array index inside the loop (this is not mandatory but makes it easy to read/understand/maintain).
Sub array_cars() 'declaring variable while defining its size Dim arr_my_cars1(5) As Variant 'initialize array elements for one array arr_my_cars1(0) = "Benz" arr_my_cars1(1) = "Maruthi" arr_my_cars1(2) = "Hyundai" arr_my_cars1(3) = "Ford" arr_my_cars1(4) = "Nissan" 'print all elements of the array For i = LBound(arr_my_cars1) To UBound(arr_my_cars1) Debug.Print arr_my_cars1(i) Next End Sub
Output of the Program:
Benz
Maruthi
Hyundai
Ford
Nissan
Program to Write and Read Array Contents
This program slightly varies from the one above. Here you will create an array and iterate through it using its indices.
Values are given to each array item using a “for” loop initially. (This was not the case in the previous program.)
Then, all the data stored in each element of the same array are read/printed back using another “for” loop.
Two loops are used here one below the other:
- One to write data to array
- Another one to read data from the same array.
Sub array_check_demo1() ' Declaration of array variable Dim arr1(11) ' Assign values to array elements For i = LBound(arr1) To UBound(arr1) 'Allocate data for each array item through a loop arr1(i) = Cells(i + 2, 1).Value Next ' Print values of the array For i = LBound(arr1) To UBound(arr1) 'Read data of each array item through a loop Debug.Print arr1(i) Next End Sub
Input is taken from the table below:
Principal amount | No of yrs | Age of customer |
10000 | 5 | 67 |
340600 | 6 | 45 |
457800 | 8 | 34 |
23400 | 3 | 54 |
12000 | 4 | 23 |
23545 | 4 | 56 |
345243 | 2 | 55 |
34543 | 3 | 24 |
23223 | 2 | 19 |
3656 | 1 | 65 |
Output of the Program
Program That Uses the [step] Value
Check out this program and try to find out why the numbers are not continuous in the output:
Sub step_demo() ' declare a counter Dim p As Integer 'loop through 10 numbers and print them For p = 1 To 10 step 3 Debug.Print p Next End Sub
Output of the Program
1
4
7
10
Yes, you might have found that the iterator variable increments by “3” instead of “1” in every iteration. Hence, the numbers printed are skip counted by “3.”
Try the same with different values in the place of [step] to understand it better if you are still confused.
The Nested “For” Loop
A loop within a loop is called a nested loop.
Structure
Let me explain this structure with colors:
- The for loop structure in yellow color is the outermost loop.
- The for loop structure/block in green color is the inner loop for the outermost (yellow color) loop. But it also acts as the outer loop for the “for loop” structure in turquoise color.
- The for loop structure in turquoise color is the innermost loop.
In this way , we can have any number of nested loops.
But there are ample chances for you to get confused when you see your own code after several days. You will wonder inside which loop is a specific line and what role it plays in the whole code.
To avoid this, follow the tips below while you code your logic:
- Maintain the alignment in your code with proper tab spaces as shown in the structure above. This can help you find the block of code/loop in which your statement is.
If possible, use the iterator variable next to the “next” keyword. It can help you indicate which “next” statement marks the closure of which loop. This is also marked in the colored structure for reference.
A Few Examples of Nested For Loops
Program to Format Cells with a Specific Word
This program iterates through all the cells (every column of every row in this case). If the cell content has a word “India,” then the specified formatting is applied to it.
Sub format_cell_with() For i = 1 To 15 For j = 1 To 5 cellcontent = Cells(i, j).Value If InStr(cellcontent, "India") &amp;gt; 0 Then With Cells(i, j).Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .ThemeColor = xlThemeColorAccent2 .TintAndShade = 0.399975585192419 .PatternTintAndShade = 0 End With End If Next Next
Input sheet:
ICC Men’s Cricket World Cup Winners – 50 Overs | ||||
Year | World Cup Winner | Runners Up | Host | Finals Venue |
1975 | West Indies | Australia | England | Lord’s Cricket Ground, London |
1979 | West Indies | England | England | Lord’s Cricket Ground, London |
1983 | India | West Indies | England | Lord’s Cricket Ground, London |
1987 | Australia | England | India & Pakistan | Eden Gardens, Kolkata |
1992 | Pakistan | England | Australia & New Zealand | Melbourne Cricket Ground, Melbourne |
1996 | Sri Lanka | Australia | India, Pakistan & Sri Lanka | Gaddafi Stadium, Lahore |
1999 | Australia | Pakistan | England | Lord’s Cricket Ground, London |
2003 | Australia | India | Australia | Wanderers, Johannesburg |
2007 | Australia | Sri Lanka | West Indies | Kensington Oval, Bridgetown |
2011 | India | Sri Lanka | India | Wankhede Stadium, Mumbai |
2015 | Australia | New Zealand | Australia | Melbourne Cricket Ground |
2019 | England | New Zealand | England | Lord’s, London |
2023 | — | — | India | — |
Output sheet – after the program is run:
Program with 2D Array and “NESTED FOR” Loop
This program declares a two dimensional array and initializes data in all its elements.
The first dimension holds the students’ names, and the second dimension holds the “exam results” of the students in the first dimension. These are written back to an Excel sheet.
Warning: As the code does not select any sheet in specific, please ensure that you keep a blank Excel sheet selected. This can prevent any damage to your existing data.
In case you wish to learn more about multidimensional arrays, please check out this article.
Sub Nested_for_demo2() 'declaring and defining size of an array '3 means 4 rows starting from 0 to 3 and 1 means 2 columns starting from 0 to 1 Dim arr_stu(1 To 5, 1 To 2) As Variant 'initialize array elements arr_stu(1, 1) = "Dave" arr_stu(1, 2) = "Fail" arr_stu(2, 1) = "Trumpo" arr_stu(2, 2) = "Pass" arr_stu(3, 1) = "Vincent" arr_stu(3, 2) = "Pass" arr_stu(4, 1) = "Rose Mary" arr_stu(4, 2) = "Pass" arr_stu(5, 1) = "Eliza" arr_stu(5, 2) = "Fail" ' print all elements to the open excel sheet. For i = 1 To 5 For j = 1 To 2 Cells(i, j) = arr_stu(i, j) Next j Next End Sub
Output of the Program on the Active Excel Sheet: Here
- The rows indicate the “i” value of the array (first dimension) and the iterator variable of the outer “for” loop.
- The columns indicate the “j” value of the array (Col A – first dimension , Col B – second dimension) and the iterator variable of the inner “for” loop.
The “Continue” Statement in Visual Basic: Skip a Part of an Iteration
When you encounter a situation where you wish to skip running the rest of the code inside the loop for a specific iteration based on a condition, the “continue” statement will come to your rescue in Visual Basic Programming.
Continue
Syntax:
Continue { Do | For | While }
Where { Do | For | While }
are the respective loops in which it has to be used.
A Simple Example
Sub continue_demo() ' declare a counter Dim i As Integer 'loop through 10 numbers and print them For i = 1 To 10 ' we will skip printing "4" If i = 4 Then Continue For End Debug.Print i Next End Sub
Your output will not have “4” in this case. As the condition is met in the 4th iteration, the continue statement is hit and the rest of the code is skipped for that iteration. The control then moves to the “next” statement of the loop (inner loop in case of nested loops).
Note: The Next
statement is the closure of a loop, as you may be aware.
Output of the above program
1
2
3
5
6
7
8
9
10
Continue Statement is Not Available in VBA
VBA does not offer the “continue statement” because well-built logic in a loop can help us avoid using a “continue” statement. For example, rearranging statement blocks like nested loops and if conditions can help avoid the use of “continue” statements.
An Alternative to the Continue Statement
In unavoidable situations, the Goto statement can be used.
This article can provide you with more insights on how to properly use the “Goto” statement in VBA.
Conclusion
In my experience, I would say that the “for” loop is my favorite compared to the “do while “/“Do until”/“ For each” loops. The reason is the comfort of defining it completely in one line. Even during run-time, you can find how many iterations are completed and how many are yet to come.
I have also been able to use this loop in situations where I do not know the number of iterations. I manage it using conditions inside the loop. It also comes handy when I want to wait for a page load during automation. Once you start using this loop, you will even start playing around nested “for loops” with much more confidence and fewer of mistakes.
So, what are you waiting for ? Why not give it a try? 😊
-
#2
Are you asking a question ? OR you are looking forward for a confirmation of the answer to your question ?
-
#3
i’m looking for the keyword for continue statement in VBA. In java, there is continue keyword. but i’m not sure whether VBA have or not. i need to use the continue keyword to interate my looping
Are you asking a question ? OR you are looking forward for a confirmation of the answer to your question ?
-
#4
Ok, so your question is proper as you wanna know the syntax that can be replaced for the iteration in your program.
A friendly suggestion mate…dont complicate yourself comparing Java with VBA…you bet this is way too different in terms of syntax and logic as well…I am a JCP but here I am so a learner in VBA and I do follow a primary principle «never to compare java syntax with VBA» else you wud mess with your Java funda as well !
-
#5
Hi Stormseed,
Thanks for your golden advise. I thinking to explore further as i’m not sure whether the VBA have the syntax/keywords. if wud be good if there is such syntax.. right…
thanks
Regards
Yee Khoon
A friendly suggestion mate…dont complicate yourself comparing Java with VBA…you bet this is way too different in terms of syntax and logic as well…I am a JCP but here I am so a learner in VBA and I do follow a primary principle «never to compare java syntax with VBA» else you wud mess with your Java funda as well !
-
#6
Yee Khon
What exactly are you trying to do?
As far as I’m aware there is no equivalent of Continue in VBA.
But there are probably other methods to achieve what you want.
-
#7
Hi Norie,
Again, thanks for replying my post…
oh yeah… now i thinking to use the Goto syntax to achieve in my loop.
what i’m exectly want to do is that
Code:
for i = 0 to ubound(dataArray)
if left(dataArray(i,3), 1) ="z" then continue
cells(i,1).value = dataArray(i,1)
next i
Yee Khon
What exactly are you trying to do?
As far as I’m aware there is no equivalent of Continue in VBA.
But there are probably other methods to achieve what you want.
-
#8
Yee Khon
I’m sorry but it still isn’t clear what you want to do.
If you want to exit the for loop based then use Exit For.
-
#9
Hi Yee
As you may well know, the use of GoTo is usually considered non structured programming.
There are 4 usual GoTo variations, the GoTo itsef and its pals Break (Exit in vba), Continue (no equivalent in vba) and Return (also Return in vba). Any of the 4 may break the flow of the program (used inside a loop may even break the logic of the loop) and so, according to the supporters of structured programming, should simply be avoided as much as possible (some will go as far as supporting the removal of this statement from the languages). You can find lots of information about structured programming on the Web and in programming / computer science books.
So, your:
Code:
For/Do/While
' code'
If Condition then Continue
' more code'
End For/Loop
is equivalent to the also not structured:
Code:
For/Do/While
' code'
If Condition then GoTo EndLoop
' more code'
EndLoop:
End For/Loop
or, to the classical structured
Code:
For/Do/While
' code'
If Not Condition then
' more code'
End If
End For/Loop
Remark: I’m just contributing with information, I’m not saying that you should never use these statements. In some cases they may be useful and in others, for example if you use a switch construct in C/C++, unavoidable.
Hope this helps
PGC
-
#10
Excellent information and very useful too….PGC !
thanks a lot for the explanation.
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
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
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!
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
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
This Excel tutorial explains how to use Continue in the VBA debugging environment in Excel 2016 (with screenshots and step-by-step instructions).
Continue
While in debug mode, you can «Continue» your VBA code in Excel 2016.
You can choose to «Continue» execution of your code in Excel 2016. What this means is that your suspended program will continue executing from where it left off. With this option, your program should either finish running or suspend at the next breakpoint encountered.
You can do this by either pressing the F5 key or selecting «Continue» under the Run menu.
Циклы в VBA Excel предназначены для повторения одного и того же блока операторов. Количество итераций может быть задано явно, зависеть от условия или количества элементов, содержащихся в обрабатываемом объекте.
Цикл For… Next
Цикл For… Next в VBA Excel предназначен для выполнения группы операторов необходимое количество раз, заданное счетчиком — специальной переменной цикла. После выполнения каждой итерации значение счетчика увеличивается или уменьшается на единицу или на число, указанное с помощью оператора Step. Предусмотрен принудительный выход из цикла с помощью оператора Exit For. Перейти к подробному описанию …
Цикл Do While… Loop
Цикл Do While… Loop в VBA Excel предназначен для повторения блока операторов до тех пор, пока выполняется заданное условие (возвращается значение True). Этот цикл позволяет проверять условие как до, так и после выполнения операторов. Предусмотрен принудительный выход из цикла с помощью оператора Exit Do. Перейти к подробному описанию …
Цикл While… Wend
Цикл While… Wend в VBA Excel предназначен для выполнения блока операторов до тех пор, пока выполняется заданное условие (возвращается значение True). Этот цикл позволяет проверять условие только до выполнения операторов. Принудительный выход из цикла с помощью оператора Exit Do не предусмотрен. Перейти к подробному описанию …
Цикл Do Until… Loop
Цикл Do Until… Loop в VBA Excel предназначен для повторения блока операторов пока не выполняется заданное условие (возвращается значение False). Этот цикл позволяет проверять условие как до, так и после выполнения операторов. Предусмотрен принудительный выход из цикла с помощью оператора Exit Do. Перейти к подробному описанию …
Цикл For Each… Next
Цикл For Each… Next в VBA Excel предназначен для выполнения блока операторов по отношению к каждому элементу из группы элементов (диапазон, массив, коллекция). Предусмотрен принудительный выход из цикла с помощью оператора Exit For. Перейти к подробному описанию …