Vba excel продолжить for if

This can also be solved using a boolean.

For Each rngCol In rngAll.Columns
    doCol = False '<==== Resets to False at top of each column
    For Each cell In Selection
        If cell.row = 1 Then
            If thisColumnShouldBeProcessed Then doCol = True
        End If
        If doCol Then
            'Do what you want to do to each cell in this column
        End If
    Next cell
Next rngCol

For example, here is the full example that:
(1) Identifies range of used cells on worksheet
(2) Loops through each column
(3) IF column title is an accepted title, Loops through all cells in the column

Sub HowToSkipForLoopIfConditionNotMet()
    Dim rngCol, rngAll, cell As Range, cnt As Long, doCol, cellValType As Boolean
    Set rngAll = Range("A1").CurrentRegion
    'MsgBox R.Address(0, 0), , "All data"
    cnt = 0
    For Each rngCol In rngAll.Columns
        rngCol.Select
        doCol = False
        For Each cell In Selection
            If cell.row = 1 Then
                If cell.Value = "AnAllowedColumnTitle" Then doCol = True
            End If
            If doCol Then '<============== THIS LINE ==========
                cnt = cnt + 1
                Debug.Print ("[" & cell.Value & "]" & " / " & cell.Address & " / " & cell.Column & " / " & cell.row)
                If cnt > 5 Then End '<=== NOT NEEDED. Just prevents too much demo output.
            End If
        Next cell
    Next rngCol
End Sub

Note: If you didn’t immediately catch it, the line If docol Then is your inverted CONTINUE. That is, if doCol remains False, the script CONTINUES to the next cell and doesn’t do anything.

Certainly not as fast/efficient as a proper continue or next for statement, but the end result is as close as I’ve been able to get.

 

Nik021

Пользователь

Сообщений: 63
Регистрация: 24.02.2017

#1

01.08.2017 18:46:47

Добрый день.

Есть цикл for, в нем много условий и действие.
Я хочу, чтобы при определенном условии дальнейшие условия не проверялись вообще и переходить к следующему шагу.
Делать многоуровневые конструкции if else не хочется. При проверке каждого условия хочется быть уверенным, что предыдущие условия выдали положительный ответ.
Заранее спасибо.

Код
For i = 1 To 5
        
        q = False
        
        If 1 = 1 Then
            q = True
        Else
            If 1 > 2 Then
                q = True
            Else
                '   перейти к следующему шагу
            End If
        End If
        
        If 3 = 3 Then
            q = True
        Else
            '   перейти к следующему шагу
        End If
        
        
        If 5 = 6 Then
            q = True
        Else
            '   перейти к следующему шагу
        End If
        
        
        If q Then Debug.Print "выполняем действие"
        
    Next
 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

Go to?
Еще может имеет смысл присмотреться к Select Case. Но не зная конечной цели сложно точно сказать, подойдет или нет.
ElseIf тоже никто не отменял.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

как может быть 1 > 2 и 5 = 6?

 

Nik021

Пользователь

Сообщений: 63
Регистрация: 24.02.2017

The_Prist,
Go to почему-то все настоятельно рекомендуют не использовать в циклах
Select Case не поможет в моей ситуации

В каждом условии буду вдобавок проверять результат предыдущего условия, пока так…  

 

Equio

Пользователь

Сообщений: 274
Регистрация: 05.05.2016

Continue For

https://msdn.microsoft.com/en-us/library/z6zekeaa(v=vs.100).aspx

Хотя это для VB. Не знаю, будет ли в VBA работать.

Update: Попробовал, не работает в VBA.

Изменено: Equio01.08.2017 19:36:30

 

Hugo

Пользователь

Сообщений: 23251
Регистрация: 22.12.2012

#6

01.08.2017 19:33:21

Цитата
Nik021 написал:
Select Case не поможет в моей ситуации

— как часто слышали это в разных вариантах :)

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#7

01.08.2017 19:38:16

Цитата
Nik021 написал:
Go to почему-то все настоятельно рекомендуют не использовать

значит не используйте, раз Вам так рекомендуют :) Я иногда использую. К слову, если бы это было совсем уж «неграмотно» — его бы не было и в более серьезных языках. Но он там есть. Главное использовать правильно, чтобы эти GoTo не не ломали читаемость кода и главное — были оправданы. Потому как некоторые пихают их там, где без них можно обойтись более чем.
Выбора за Вами.
По поводу Select Case — уже говорил. И Hugo прав — иногда за этим «не поможет» часто стоит просто незнание всех возможностей этой конструкции. Не более.
Да и в любом случае — не видя реальной задачи подсказать больше нечего.

Изменено: The_Prist01.08.2017 19:39:18

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Nik021

Пользователь

Сообщений: 63
Регистрация: 24.02.2017

The_Prist, я искал легкий способ прекратить дальнейшее выполнение кода и перехода к следующему шагу цикла, как, например, exit for (exit полностью завершает цикл, но вы поняли). Рас так просто нельзя, то буду использовать другие доступные варианты. Спасибо.

 

Влад

Пользователь

Сообщений: 1189
Регистрация: 24.12.2012

В таких случаях внутри цикла For…Next делается замкнутый Do…Loop с командой выхода в конце. Любое условие, при котором нужно перейти к следующему шагу Next, выполняет Exit Do.

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

#10

01.08.2017 20:49:51

Цитата
Nik021 написал:
Select Case не поможет в моей ситуации

А мне кажется, что Select Case именно то, что Вам нужно.

 

Nik021

Пользователь

Сообщений: 63
Регистрация: 24.02.2017

Юрий М, Select Case, на сколько я помню, проверяет только числа, а строковые значение сравнивать не умеет или я что-то путаю уже.

Влад, а вот это уже интересная идея !)

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

#12

01.08.2017 21:57:11

Цитата
Nik021 написал:
или я что-то путаю уже.

Или )

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#13

02.08.2017 08:59:56

Цитата
Nik021 написал:
на сколько я помню, проверяет только числа

что-то Вы не то помните. Эта конструкция принимает не просто и числа и текст, но и очень такие выражения в качестве условий, для которых в If … then надо будет городить доп.условия.
Идея с Do .. Loop не очень хорошая. Делать цикл только ради того, чтобы перескочить к концу другого цикла — это уже перебор. Уж в таких случаях куда оправданнее будет тот же GoTo, чем Exit Do в тех же места, не считаете?

Изменено: The_Prist02.08.2017 09:03:02

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Влад

Пользователь

Сообщений: 1189
Регистрация: 24.12.2012

 

The_Prist

Пользователь

Сообщений: 14182
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#15

02.08.2017 13:07:26

Цитата
Влад написал:
Не перевариваю GoTo

Это выбор каждого :) И если мне приведут вменяемое обоснование, чем он так плох — может тоже не буду использовать. Пока что не нашел причин отказываться от него совсем, особенно в ситуациях, где с ним процедура намного лаконичнее, читабельнее и быстрее, чем без него.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Ігор Гончаренко

Пользователь

Сообщений: 13746
Регистрация: 01.01.1970

#16

02.08.2017 14:40:01

и тем более GOTO логически и визуальнео очень органично встраивается в представленнй макрос
достаточно заменить комментарии ‘   перейти к следующему шагу на GOTO Метка, а саму метку поставить перед Next

Скрытый текст

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

 

kuklp

Пользователь

Сообщений: 14868
Регистрация: 21.12.2012

E-mail и реквизиты в профиле.

#17

02.08.2017 14:51:01

Цитата
Ігор Гончаренко написал:
логически и визуальнео очень органично встраивается

тоже сделает ElseIf конструкция без всяких гот и меток ;)

Я сам — дурнее всякого примера! …

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

vba else if statement

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

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!

automacro

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

vba nested for loop

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

Цикл For… Next в VBA Excel, его синтаксис и описание отдельных компонентов. Примеры использования цикла For… Next.

Цикл For… Next в VBA Excel предназначен для выполнения группы операторов необходимое количество раз, заданное управляющей переменной цикла — счетчиком. При выполнении цикла значение счетчика после каждой итерации увеличивается или уменьшается на число, указанное выражением оператора Step, или, по умолчанию, на единицу. Когда необходимо применить цикл к элементам, количество которых и индексация в группе (диапазон, массив, коллекция) неизвестны, следует использовать цикл For Each… Next.


For counter = start To end [ Step step ]

    [ statements ]

    [ Exit For ]

    [ statements ]

Next [ counter ]


For счетчик = начало To конец [ Step шаг ]

    [ операторы ]

    [ Exit For ]

    [ операторы ]

Next [ счетчик ]


В квадратных скобках указаны необязательные атрибуты цикла For… Next.

Компоненты цикла For… Next

Компонент Описание
counter Обязательный атрибут. Числовая переменная, выполняющая роль счетчика, которую еще называют управляющей переменной цикла.
start Обязательный атрибут. Числовое выражение, задающее начальное значение счетчика.
end Обязательный атрибут. Числовое выражение, задающее конечное значение счетчика.
Step* Необязательный атрибут. Оператор, указывающий, что будет задан шаг цикла.
step Необязательный атрибут. Числовое выражение, задающее шаг цикла. Может быть как положительным, так и отрицательным.
statements Необязательный** атрибут. Операторы вашего кода.
Exit For Необязательный атрибут. Оператор выхода из цикла до его окончания.
Next [ counter ] Здесь counter — необязательный атрибут. Это то же самое имя управляющей переменной цикла, которое можно здесь не указывать.

*Если атрибут Step отсутствует, цикл For… Next выполняется с шагом по умолчанию, равному 1.

**Если не использовать в цикле свой код, смысл применения цикла теряется.

Примеры циклов For… Next

Вы можете скопировать примеры циклов в свой модуль VBA, последовательно запускать их на выполнение и смотреть результаты.

Простейший цикл

Заполняем десять первых ячеек первого столбца активного листа Excel цифрами от 1 до 10:

Sub test1()

Dim i As Long

  For i = 1 To 10

    Cells(i, 1) = i

  Next

End Sub

Простейший цикл с шагом

В предыдущий цикл добавлен оператор Step со значением 3, а результаты записываем во второй столбец:

Sub test2()

Dim i As Long

  For i = 1 To 10 Step 3

    Cells(i, 2) = i

  Next

End Sub

Цикл с отрицательными аргументами

Этот цикл заполняет десять первых ячеек третьего столбца в обратной последовательности:

Sub test3()

Dim i As Long

  For i = 0 To 9 Step 1

    Cells(i + 10, 3) = i + 10

  Next

End Sub

Увеличиваем размер шага до -3 и записываем результаты в четвертый столбец активного листа Excel:

Sub test4()

Dim i As Long

  For i = 0 To 9 Step 3

    Cells(i + 10, 4) = i + 10

  Next

End Sub

Вложенный цикл

Внешний цикл последовательно задает индексы первых десяти строк активного листа, а вложенный цикл складывает числа в первых четырех ячейках строки с текущем индексом и записывает сумму в ячейку пятого столбца. Перед запуском вложенного цикла с накопительным сложением, пятую ячейку соответствующей строки обнуляем, чтобы в случае нахождения в ней какого-либо числа, оно не прибавилось к итоговой сумме.

Sub test5()

Dim i1 As Long, i2 As Long

  For i1 = 1 To 10

‘Пятой ячейке в строке i1 присваиваем 0

    Cells(i1, 5) = 0

      For i2 = 1 To 4

        Cells(i1, 5) = Cells(i1, 5) + Cells(i1, i2)

      Next

  Next

End Sub

Выход из цикла

В шестой столбец активного листа запишем названия десяти животных, конечно же, с помощью цикла For… Next:

Sub test6()

Dim i As Long

  For i = 1 To 10

    Cells(i, 6) = Choose(i, «Медведь», «Слон», «Жираф», «Антилопа», _

    «Крокодил», «Зебра», «Тигр», «Ящерица», «Лев», «Бегемот»)

  Next

End Sub

Следующий цикл будет искать в шестом столбце крокодила, который съел галоши. В ячейку седьмого столбца цикл, пока не встретит крокодила, будет записывать строку «Здесь был цикл», а когда обнаружит крокодила, запишет «Он съел галоши» и прекратит работу, выполнив команду Exit For. Это будет видно по ячейкам рядом с названиями животных ниже крокодила, в которых не будет текста «Здесь был цикл».

Sub test7()

Dim i As Long

  For i = 1 To 10

    If Cells(i, 6) = «Крокодил» Then

      Cells(i, 7) = «Он съел галоши»

      Exit For

        Else

      Cells(i, 7) = «Здесь был цикл»

    End If

  Next

End Sub


Результат работы циклов For… Next из примеров:

Результат работы циклов For... Next из примеров

Результат работы циклов For… Next

Такие данные на активном листе Excel вы получите, если последовательно запустите на выполнение в редакторе VBA все семь подпрограмм из примеров, демонстрирующих работу циклов For… Next.

Цикл с дробными аргументами

Атрибуты start, end и step могут быть представлены числом, переменной или числовым выражением:

For i = 1 To 20 Step 2

For i = a To b Step c

For i = a 3 To 2b + 1 Step c/2  

В результате вычисления значения переменной вне цикла или выражения внутри его может получиться дробный результат. VBA Excel округлит его до целого числа, используя бухгалтерское округление:

‘Значения атрибутов до округления

For i = 1.5 To 10.5 Step 2.51

‘Округленные значения атрибутов

For i = 2 To 10 Step 3  

Старайтесь не допускать попадания в тело цикла For… Next неокругленных значений аргументов, чтобы не получить непредсказуемые результаты его выполнения. Если без дробных чисел не обойтись, а необходимо использовать обычное округление, применяйте в коде VBA функцию рабочего листа WorksheetFunction.Round для округления числа перед использованием его в цикле For… Next.


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:

  1. Do until
  2. Do while
  3. For
  4. 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;amp; " X " &amp;amp;amp; input_number &amp;amp;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.

A sample output of this program if “3” is input by the user.

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:

  1. One to write data to array
  2. 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

Output of the "for" loop 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

Structure of a nested loop within a loop.

Let me explain this structure with colors:

  1. The for loop structure in yellow color is the outermost loop. 
  2. 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.
  3. 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:

  1. 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;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:

Output sheet after a program to format cells with a specific word 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 

  1. The rows indicate the “i” value of the array (first dimension) and the iterator variable of the outer “for” loop.
  2. 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? 😊

Понравилась статья? Поделить с друзьями:
  • Vba excel программирование уроки
  • Vba excel проверка ячейки на ошибку
  • Vba excel проверка типов данных
  • Vba excel проверка существования объекта
  • Vba excel проверка символа в ячейке