Vba для excel оператор цикла

Циклы в 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. Перейти к подробному описанию …

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

На чтение 13 мин. Просмотров 26.5k.

VBA While Loop

Рамакришна, Источники индийской мудрости

Сейчас … мы идем по кругу

Эта статья содержит полное руководство по VBA Do While и VBA While Loops. (Если вы ищете информацию о циклах VBA For и For Each, перейдите сюда)

Цикл VBA While существует, чтобы сделать его совместимым со старым кодом. Однако Microsoft рекомендует использовать цикл Do Loop, поскольку он более «структурирован и гибок». Оба этих цикла рассматриваются в этом посте.

Для быстрого ознакомления с этими циклами перейдите к таблице быстрого руководства ниже.

Если вы ищете что-то конкретное, вы можете посмотреть содержание ниже.

Содержание

  1. Краткое руководство по VBA While Loops
  2. Введение
  3. Цикл For против цикла Do While
  4. Условия
  5. Формат цикла Do
  6. Цикл Exit Do
  7. While Wend
  8. Бесконечный цикл
  9. Использование функций Worksheet вместо циклов
  10. Резюме

Краткое руководство по VBA While Loops

Формат цикла Описание Пример
Do While … Loop Запускается 0 или более раз, пока условие выполняется Do While result = «Верно»
Loop
Do … Loop While Запускается 1 или более раз, пока условие выполняется Do 
Loop While result = «Верно»
Do Until … Loop Запускается 0 или более раз, пока условие не будет выполнено Do Until result <> «Верно»
Loop
Do … Until Loop Запускается 1 или более раз, пока условие не будет выполнено Do 
Loop Until result <> «Верно»
While … Wend
R
Запускается 0 или более раз, пока условие истинно.
Примечание: этот цикл считается устаревшим.
While result = «Верно»
Wend
Exit the Do Loop Завершает Do Do While i < 10
   i = GetTotal
   If i < 0 Then
      Exit Do
   End If
Loop

Введение

Если вы никогда ранее не использовали циклы, тогда вы можете прочитать «Что такое циклы и зачем они вам нужны» из моего поста в журнале For Loop.

Я собираюсь сосредоточиться в основном на Do Loop в этой статье. Как я упоминал выше, мы видели, что цикл While Wend считается устаревшим. Для полноты информации я все равно его включил в эту статью.

Итак, во-первых, зачем нам нужны циклы Do While, когда у нас уже есть циклы For?

Цикл For против цикла Do While

Когда мы используем цикл For Loop, мы заранее знаем, сколько раз мы хотим его запустить. Например, мы можем захотеть запустить цикл один раз для каждого элемента в коллекции, массиве или словаре.

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

' запускается 5 раз
For i = 1 To 5

' запускается один раз для каждого элемента коллекции
For i = 1 To coll.Count

' запускается один раз для каждого элемента в arr
For i = LBound(arr) To coll.lbound(arr)

' запускается один раз для каждого значения от 1 до значения в lastRow
For i = 1 To lastRow

' запускается один раз для каждого элемента в коллекции
For Each s In coll

Цикл Do другой. Он работает:

  • В то время как условие верно
  • Пока условие не будет выполнено

Другими словами, количество циклов в большинстве случаев не имеет значения.

Итак, что такое условие и как мы их используем?

Условия

Условие — это утверждение, которое оценивается как истинное или ложное. Они в основном используются с операторами Loops и If. При создании условия вы используете такие знаки, как >, <, <>,> =, =.

Ниже приведены примеры условий

Условие Истина, когда…
x < 5 x меньше 5
x <= 5 x меньше либо равен 5
x > 5 x больше 5
x >= 5 x больше либо равен 5
x = 5 x равен 5
x <> 5 x не равен 5
x > 5 And x < 10 x больше 5 И меньше 10
x = 2 Or x >10 x равен 2 ИЛИ больше 10
Range(«A1») = «Иван» Ячейка A1 содержит текст «Иван»
Range(«A1») <> «Иван» Ячейка A1 не содержит текст «Иван»

Вы могли заметить x = 5 как условие. Его следует путать с х = 5, при использовании в качестве назначения.

Например

' означает: значение 6 будет храниться в х
x = 6

' означает: х равен 6?
If x = 6

' означает: х равен 6?
Do While x = 6

В следующей таблице показано, как «=» используется в условиях и назначениях.

Использование «=» Тип Имеется в виду
Loop Until x = 5 Условие x равен 5?
Do While x = 5 Условие x равен 5?
If x = 5 Then Условие x равен 5?
For x = 1 To 5 Присваивание Установите значение x = 1, затем = 2 и т.д.
x = 5 Присваивание Установите значение x=5
b = 6 = 5 Присваивание и
условие
Присвойте b
результату условия
6 = 5
x = MyFunc(5,6) Присваивание Присвойте х
значение,
возвращаемое
функцией

Формат цикла Do

Цикл Do можно использовать четырьмя способами, и это часто вызывает путаницу. Однако в каждом из этих четырех способов есть только небольшая разница.

Do всегда в начале первой строки, а Loop всегда в конце последней строки.

Мы можем добавить условие после любой строки.

Do [условие]
Loop

Do 
Loop [условие]

Условию предшествует While или Until, которое дает нам эти четыре возможности

Do While [условие]
Loop

Do Until [условие]
Loop

Do 
Loop While [условие]

Do 
Loop Until [условие]

Давайте посмотрим на некоторые примеры, чтобы прояснить это.

Примеры цикла Do

Представьте, что вы хотите, чтобы пользователь ввел список элементов. Каждый раз, когда пользователь вводит элемент, вы печатаете его в «Immediate Window». Когда пользователь вводит пустую строку, вы хотите, чтобы приложение закрывалось.

В этом случае цикл For не подойдет, поскольку вы не знаете, сколько элементов будет вводить пользователь. Пользователь может ввести пустую строку первым или с сотой попытки. Для этого типа сценария вы бы использовали цикл Do.

Следующий код показывает это

 Dim sCommand As String

    Do
        ' Получить пользовательский ввод
        sCommand = InputBox("Пожалуйста, введите элемент")

        ' Печать в Immediate Window (Ctrl + G для просмотра)
        Debug.Print sCommand

    Loop While sCommand <> ""

Код входит в цикл и продолжается до тех пор, пока не достигнет строки «Loop While». На этом этапе он проверяет, оценивается ли условие как истинное или ложное.

Если условие оценивается как ложное, то код выходит из цикла и продолжается.
Если условие оценивается как истинное, то код возвращается к строке Do и снова проходит через цикл.
Разница между наличием условия на линии Do и на линии Loop очень проста.

Когда условие находится в строке Do, цикл может вообще не работать. Так что он будет работать ноль или более раз.
Когда условие находится на линии Loop, цикл всегда будет запущен хотя бы один раз. Так что он будет запущен один или несколько раз.

В нашем последнем примере условие находится в строке Loop, потому что мы всегда хотим получить хотя бы одно значение от пользователя. В следующем примере мы используем обе версии цикла. Цикл будет выполняться, пока пользователь не введет букву «н».

Sub GetInput()

    Dim sCommand As String

    ' Условие в начале
    Do While sCommand <> "н"
        sCommand = InputBox("Пожалуйста, введите элемент для цикла 1")
    Loop

    ' Условие в конце
    Do
        sCommand = InputBox("Пожалуйста, введите элемент для цикла 2")
    Loop While sCommand <> "н"

End Sub

В приведенном выше примере оба цикла будут вести себя одинаково.

Однако, если мы установим для sCommand значение «н» до запуска цикла «Do While», код не войдет в цикл.

Sub GetInput2()

    Dim sCommand As String
    sCommand = "н"

    ' Цикл не будет работать, поскольку команда "н"
    Do Whilel sCommand <> "н"
        sCommand = InputBox("Пожалуйста, введите элемент для цикла 1")
    Loop

    ' Цикл все равно будет запущен хотя бы один раз
    Do
        sCommand = InputBox("Пожалуйста, введите элемент для цикла 2")
    Loop While sCommand <> "н"

End Sub

Второй цикл в вышеприведенном примере (то есть Loop While) всегда будет запускаться хотя бы один раз.

While против Until

При использовании Do Loop условию должно предшествовать Until или While.

Until и While, по сути, противоположны друг другу. Они используются в VBA аналогично тому, как они используются в английском языке.

Например:

  • Оставьте одежду, пока не пойдет дождь
  • Оставь одежду, пока не идет дождь

Другой пример:

  • Оставайся в постели, пока не станет светло
  • Оставайся в постели, пока темно

Еще один пример:

  • повторять, пока число не станет больше или равно десяти
  • повторить пока счет меньше десяти

Как видите, использование Until и While — это просто противоположный способ написания одного и того же условия.

Примеры Until и While

Следующий код показывает циклы «While» и «Until» рядом. Как видите, единственная разница в том, что условие полностью изменено.

Примечание: знаки <> означают «не равно».

Sub GetInput()

    Dim sCommand As String

    ' Условие в начале
    Do Until sCommand = "н"
        sCommand = InputBox("Пожалуйста, введите элемент для цикла 1")
    Loop

    Do While sCommand <> "н"
        sCommand = InputBox("Пожалуйста, введите элемент для цикла 1")
    Loop

    ' Условие в конце
    Do
        sCommand = InputBox("Пожалуйста, введите элемент для цикла 2")
    Loop Until sCommand = "н"

    Do
        sCommand = InputBox("Пожалуйста, введите элемент для цикла 2")
    Loop While sCommand <> "н"

End Sub
  • Первый цикл: запускается только в том случае, если sCommand не равен ‘н’.
  • Второй цикл: запускается только в том случае, если sCommand не равен ‘н’.
  • Третий цикл: будет запущен хотя бы один раз перед проверкой sCommand.
  • Четвертый цикл: будет запущен хотя бы один раз перед проверкой sCommand.

Пример: проверка объектов

Примером использования Until и While является проверка объектов. Когда объект не был назначен, он имеет значение Nothing.

Поэтому, когда мы объявляем переменную книги в следующем примере, она имеет значение Nothing, пока мы не назначим ее Workbook.

Противоположностью Nothing не является Nothing, что может сбить с толку.

Представьте, что у нас есть две функции: GetFirstWorkbook и GetNextWorkbook, которые возвращают некоторые объекты книги. Код будет печатать имя рабочей книги до тех пор, пока функции больше не вернут действительную рабочую книгу.

Вы можете увидеть пример кода здесь:

Dim wrk As Workbook
    Set wrk = GetFirstWorkbook()

    Do Until wrk Is Nothing
        Debug.Print wrk.Name
        Set wrk = GetNextWorkbook()
    Loop

Написание этого кода с использованием Do While было бы более запутанным, так как условие Not Is Nothing

Dim wrk As Workbook
    Set wrk = GetFirstWorkbook()

    Do While Not wrk Is Nothing
        Debug.Print wrk.Name
        Set wrk = GetNextWorkbook()
    Loop

Это делает код более понятным, и наличие четких условий — всегда хорошо. Честно говоря, разница маленькая, и выбор между «While» и «Until» действительно сводится к личному выбору.

Цикл Exit Do

Мы можем выйти из любого цикла Do с помощью оператора Exit Do.

Следующий код показывает пример использования Exit Do

Do While i < 1000
     If Cells(i,1) = "Найдено" Then 
         Exit Do
     End If
     i = i + 1
Loop 

В этом случае мы выходим из цикла Do Loop, если ячейка содержит текст «Найдено».

While Wend

Этот цикл в VBA, чтобы сделать его совместимым со старым кодом. Microsoft рекомендует использовать циклы Do, поскольку они более структурированы.

Из MSDN: «Оператор Do… Loop обеспечивает более структурированный и гибкий способ выполнения циклов».

Формат цикла VBA While Wend

Цикл VBA While имеет следующий формат:

While <Условие>
Wend

While Wend против Do

Разница между циклами VBA While и VBA Do заключается в следующем:

  1. While может иметь условие только в начале цикла.
  2. While не имеет версии Until.
  3. Не существует оператора для выхода из цикла While, как Exit For или Exit Do.

Условие для цикла VBA While такое же, как и для цикла VBA Do While. Два цикла в приведенном ниже коде работают точно так же.

Sub GetInput()

    Dim sCommand As String

    Do While sCommand <> "н"
        sCommand = InputBox("Пожалуйста, введите элемент для цикла 1")
    Loop

    While sCommand <> "н"
        sCommand = InputBox("Пожалуйста, введите элемент для цикла 2")
    Wend

End Sub

Бесконечный цикл

Даже если вы никогда не писали код в своей жизни, я уверен, что вы слышали фразу «Бесконечный цикл». Это цикл, в котором условие никогда не будет выполнено. Обычно это происходит, когда вы забыли обновить счетчик.

Следующий код показывает бесконечный цикл

Dim cnt As Long
    cnt = 1

    'это бесконечный цикл
    Do While cnt <> 5

    Loop

В этом примере cnt установлен в 1, но он никогда не обновляется. Поэтому условие никогда не будет выполнено — cnt всегда будет меньше 5.

В следующем коде cnt обновляется каждый раз, поэтому условие будет выполнено.

Dim cnt As Long
    cnt = 1

    Do While cnt <> 5
        cnt = cnt + 1
    Loop

Как вы можете видеть, использование For Loop безопаснее для подсчета, поскольку оно автоматически обновляет счет в цикле. Ниже приведен тот же цикл с использованием For.

Dim i As Long
    For i = 1 To 4

    Next i

Это явно лучший способ сделать это. Цикл For устанавливает начальное значение, условие и счет в одну строку.

Конечно, можно использовать бесконечный цикл, используя For — это потребует немного больше усилий 🙂

 Dim i As Long
    ' Бесконечный цикл
    For i = 1 To 4
        ' i никогда не достигнет 4
        i = 1
    Next i

Работа с бесконечным циклом

Когда у вас бесконечный цикл — VBA не выдаст ошибку. Ваш код будет продолжать работать, а редактор Visual Basic не будет отвечать.

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

Вы также можете выйти из цикла, убив процесс. Нажмите Ctrl + Shift + Esc. На вкладке Процессы найдите Excel / Microsoft Excel. Щелкните правой кнопкой мыши по этому и выберите «Завершить процесс». Это закроет Excel, и вы можете потерять часть работы — так что гораздо лучше использовать Ctrl + Break или его эквивалент.

Использование функций Worksheet вместо циклов

Иногда вы можете использовать функцию листа вместо цикла.

Например, представьте, что вы хотите добавить значения в список ячеек. Вы можете сделать это с помощью цикла, но было бы более эффективно использовать функцию таблицы Sum. Это быстрее и экономит много кода.

Использовать функции рабочего листа очень просто. Ниже приведен пример использования Sum и Count.

Sub WorksheetFunctions()

    Debug.Print WorksheetFunction.Sum(Range("A1:A10"))

    Debug.Print WorksheetFunction.Count(Range("A1:A10"))

End Sub

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

Sub SumWithLoop()

    Dim total As Long, count As Long
    Dim rg As Range
    For Each rg In Range("A1:A10")
        ' Total
        total = total + rg
        ' Count
        If rg <> "" Then
            count = count + 1
        End If
    Next rg

    Debug.Print total
    Debug.Print count

End Sub

Резюме

Цикл Do While

  • Цикл Do можно использовать 4 способами.
  • Его можно использовать в начале или в конце, Do While .. Loop, Do … Loop While
  • Может использоваться с Until в начале или в конце, Do Until .. Loop, Do … Loop Until
  • While и Until используют противоположные условия друг к другу.
  • Бесконечный цикл происходит, если ваше условие выхода никогда не будет выполнено.
  • Иногда использование функции рабочего листа более эффективно, чем использование цикла.

Цикл While Wend

  • Цикл Wend Wend устарел, и вы можете вместо этого использовать цикл Do.

Циклы в VBA

​Смотрите также​nilem​А остальные не​ другая структура файла​1 | товар2​ включая необязательное ключевое​ i = 1;​ в Excel​Yurasha​ Y |​ будет через макрос,​ буде очень благодарен!​

​ напр AZ1 )​

  • ​при помощи цикла​
  • ​ Do While iFib_Next​
  • ​ этот оператор, программа​

​1​Встречаются ситуации, когда от​: ВПР() с кнопочкой​

Оператор цикла «For» в Visual Basic

​ «опускаются» до уровня​​ можно было бы​​ |​ слово Step. При​ i < 100;​Полосатый жираф алик​: Спасибо большое, Светлый!!!​​|3 | C​​ но, можно и​​Спасибо!​​В1=ЕСЛИ (A1<>C1;ТДАТА ();B1)​

Цикл «For … Next»

​Do Until​​ < 1000 If​​ завершает выполнение цикла​. Однако, в некоторых​ программы VBA требуется​200?’200px’:»+(this.scrollHeight+5)+’px’);»>Sub Макрос1()​ форумы Excel.​ ВПР использовать с​1 | ………..​ включении ключевого слова​ i++) sheet.Cells[1, i]​

​: Да, ну! И​Все супер, работает!​ | $| c|​ через формулу. В​Guest​

​С1=ЕСЛИ (B1;A1)​​извлекаются значения из​​ i = 1​​ и переходит к​​ случаях требуется использовать​ совершить несколько раз​With Range(«A2:A» &​Внести ясность может​ незакрепленным диапазоном.​ |​ Step необходимо задавать​ = i; app.Visible​ без VBA можно​ Сейчас я попробую​​ Z |​​ них, к сожалению,​​: =ПРОСМОТР(9E+307;$D4:W4)​​Столбец «В» -​

​ всех ячеек столбца​ Then ‘особый случай​ выполнению операторов, находящихся​ другие значения приращения​ подряд один и​​ Cells(Rows.Count, 1).End(xlUp).Row).Offset(, 2)​​ только автор вопроса​Balbasochka​2 | Подгруппа​​ значение для изменения​​ = true; }​ обойтись. В А1​ разобрать принцип действия​|4 | D​ не силен, опыт​Guest​​ имеет формат «Дата»​​A​ для первого элемента​

​ в коде сразу​ для цикла. Это​ тот же набор​.FormulaR1C1 = «=VLOOKUP(TRIM(RC[-2]),’таблица​Гость​

​: Ух-ты, ух-ты! А​ B |​ переменной «i».​​ }​​ пишем начальное значение.​​ этих формул. «Универсальная»​​ | $| d|​ нулевой. Похожие темы​: .​Общий недостаток для​рабочего листа до​

​ последовательности iStep =​ после данного цикла.​ можно сделать при​ действий (то есть​

​ 2′!R2C1:R200C2,2,0)»​: Добрый день!​ у Вас работает!​1 | товар1​Пример №1:​

​piloterist​​ В В1 -​​ решила эту задачу​​ $ |​​ читал на этом​alexfa88​ всех всех циклических​ тех пор, пока​

Цикл «For Each»

​ 1 iFib =​​ Это можно использовать,​​ помощи ключевого слова​​ повторить несколько раз​​.Value = .Value​расчет правильный в​Сейчас попробую.​ |​​В нижеуказанном примере,​​: C# a=sheet.cells[5,10];присвоит переменной​ формулу (зависимость от​ на все 100​|5 | E​ форуме, есть очень​: Спасибо! все отлично​​ формул:​​ в столбце не​ 0 Else ‘сохраняем​ например, для поиска​

​Step​ один и тот​End With​ Вашей таблице, мне​Боже…какая она красивая​1 | товар5​

Оператор прерывания цикла «Exit For»

​ на активном листе,​​ «a» значение находящиеся​​ А1) -(это минус)​ процентов.​ | $| $|​ похожие решения, но​ работает!​должны быть включены​ встретится пустая ячейка:​ размер следующего приращения​ определённого значения в​, как показано в​ же блок кода).​End Sub​ бы сделать это​ и простая! Как​ |​ по ячейкам А1:А10​ в пятой строке​ А1. Для большей​Спасибо еще раз!​ $ |​

​ доработать их не​​не знал про​​ итерации.​iRow = 1​ перед тем, как​ массиве. Для этого​ следующем простом примере.​ Это может быть​​BOOM​​ по кнопочке, макросом.​ же мозг так​

​1 | …….. |​ проставляется значение от​ 10-ого столбца?​ точности результат можно​ Удачи!!! =)​———————​ могу, вседствие малоопытности.​

Цикл «Do While» в Visual Basic

​ эту функцию, ВПР,​​но иногда, при​​ Do Until IsEmpty(Cells(iRow,​ перезаписать ‘текущее значение​ при помощи цикла​For d =​ сделано при помощи​​: большое спасибо. Вот​​ На одном листе​ заточен? Короткие запросы…красотища!​​2 | Подгруппа​​ одного до десяти.​Вот код:​ умножить на 1000.​

​Светлый​Впоследствии я смогу​ Итак…​ ГПР, ИНДЕКС и​ запуске файла, интерация​ 1)) ‘Значение текущей​ последовательности iStep =​ просматривается каждый элемент​ 0 To 10​ циклов VBA.​ это то, что​ храниться таблица с​ А мой мозг​ С |​Sub example1 ()​C# excelapp =​ Стоя в В1​: Пожалуйста.​ удалить из итоговой​…Требуется подобрать текстовые​ ПОИСКПОЗ использую давно,а​ принимает значение по​ ячейки сохраняется в​ iFib iFib =​ массива. Как только​ Step 0.1 dTotal​К циклам VBA относятся:​ нужно)​ наименованиями и символами,​ куда-то пошел…в какие-то​1 | товар1​ Dim i As​ new Excel.Application(); excelapp.Visible​ выбираем — Меню​Но тему всё-таки​ ячейки результаты, содержащие​ сочетания содержимого ячеек,​ эту не знал​ умолчанию ( т.​ массиве dCellValues dCellValues(iRow)​ iFib_Next End If​ искомый элемент найден,​ = dTotal +​Цикл For​sergey_klip​ а на другой​ дебри…​ |​ Long For i​ = false; excelapp.DisplayAlerts​ — Сервис -​ надо переименовать. Вместо​ символы «$».​

​ но не все​​а в синтаксисе​​ е. выкл)​ = Cells(iRow, 1).Value​ ‘выводим текущее число​​ просматривать остальные нет​​ d Next d​Цикл Do While​: Привет всем. Ребят​ лист вставлялась основная​

​BOOM​​1 | товар2​​ = 1 To​ = true; excelappworkbooks​ Подбор параметра. Ячейка​ «макрос с циклом»​И сразу вопрос:​ возможные, а подчиняющиеся​ 9Е+307 — что​и тогда машина​ iRow = iRow​

​ Фибоначчи в столбце​​ необходимости – цикл​​Так как в приведённом​Цикл Do Until​ помогите. Подскажите как​

​ таблица без символов.Т.е.​: Добрый вечер, подскажите,​ |​

Цикл «Do Until» в Visual Basic

​ 10 ActiveSheet.Range(«A» &​​ = excelapp.Workbooks; excelappworkbook​​ уже высветится, результат​ написать «формулу».​​ можно ли создать​​ порядковому чередованию:​ означает?​ начинает ругаться и​ + 1 Loop​ A активного рабочего​ прерывается.​ выше примере задан​​Далее мы подробно рассмотрим​​ сообразить цикл в​​ пользователь получил таблицу​​ пожалуйста!​​1 | ……… |​​ i).Value = i​ = excelapp.Workbooks.Open(@»C:Fact» +​​ нужен 0, изменяя​​И почитайте правила.​ такой макрос, который​A1+B1+C1+D1​справку прочитал, но​

​ выскакивать сообщение о​В приведённом выше примере​ листа ‘в строке​Применение оператора​ шаг приращения равный​ каждый из этих​ теле которого с​ из 2000 строк​

​как можно вытащить​Надо получить:​​ Next i End​​ textBox3.Text + «Data.xls»,​ значение в А1​​Успехов!​​ не будет зависеть​Дано: 4 столбца​ все равно медленно​ циклических ссылках.​ условие​

​ с индексом i​Exit For​​0.1​​ циклов.​ каждой итерацией меняется​ или 20, скопировал​ данные из одной​Код уровня группы​ Sub​ Type.Missing, Type.Missing, Type.Missing,​ — ОК. Все.​DiSco​ от фиксированного числа​ с текстовыми значениями,​

​ пока что доходит​Прийдется вручную включать​

​IsEmpty(Cells(iRow, 1))​ Cells(i, 1).Value =​
​продемонстрировано в следующем​
​, то переменная​

​Структура оператора цикла​

office-guru.ru

Excel. Как в Excel сделать циклическую формулу? И будет ли «работать» формула?

​ не сколько переменных​​ ее на этот​
​ таблицы в другую,​ | Наименование |​Пример №2:​ Type.Missing, Type.Missing, Type.Missing,​
​Макс пушкарев​: Как создать цикл​ строк в столбце,​
​ количество строк во​Спасибо!​ итерации.​находится в начале​
​ iFib ‘вычисляем следующее​

​ примере. Здесь цикл​dTotal​
​For​ на величину «к»​

​ лист, нажал на​ если вторая таблица​
​ Подгруппа​В следующем примере​ Type.Missing, Type.Missing, Type.Missing,​: ну это делается​ перебирающий значения клеток?​ а будет запускать​
​ всех столбцах разное.​
​Guest​
​Demetry​ конструкции​

​ число Фибоначчи и​ перебирает 100 записей​для каждого повторения​
​в Visual Basic​ а заканчивается цикл​
​ кнопку и символа​ постоянно разная.​2 | Подгруппа​ скрываются первый и​ Type.Missing, Type.Missing, Type.Missing,​
​ через VBA скорее​ Например: A1,A2…A100?​ очередной цикл, когда​Пример:​
​: Если больше нравится​: Насчет формулы как-то​

​Do Until​​ увеличиваем индекс позиции​ массива и сравнивает​ цикла принимает значения​ может быть организована​
​ по выполнению условия​ поставились бы. Прикрепить​Т.е. Есть табл.1​
​ A |​ второй листы книги.​
​ Type.Missing, Type.Missing); excelsheets​ васего! Alt+F11​
​Что-то вроде:​
​ «наткнется» на пустую​
​______________​ ГПР, то:​ не уверен, а​, следовательно цикл будет​

можно ли задать цикл в одной формуле?

​ элемента на 1​​ каждую со значением​

​ 0.0, 0.1, 0.2,​
​ в одной из​ например e>=1​ файл я не​ с тремя столбцами:​1 | товар1​ Sub example2 ()​ = excelappworkbook.Worksheets; //Excel.Application​piloterist​Set myRange =​ ячейку?​| -|A1|B1|C1|D1|​=ГПР(9E+307;$D4:W4;1)​ функцию можно. Например,​ выполнен хотя бы​
​ iFib_Next = iFib​ переменной​ 0.3, … 9.9,​ двух форм: как​KuklP​ нашел где(((​ 1. наименование 2.​
​ | A​ Dim i As​ app = new​: Добрый день.​ ActiveSheet.Range(‘A1:A100’) For Each​В реальной задаче​|——————-​9E+307 — максимально​
​ такая:​ один раз, если​ + iStep i​dVal​
​ 10.0.​

​ цикл​​:​

​Serge_007​​ сумма 3. символ​

​1 | товар2​​ Long For i​ Microsoft.Office.Interop.Excel.Application(); //app.Workbooks.Add(Type.Missing); Excel.Worksheet​
​Подскажите пожалуйста как​ c In myRange.Cells​ в столбце A1​|1 | A​ возможное (ну или​
​Function CYCLE(m_start As​ первая взятая ячейка​ = i +​
​. Если совпадение найдено,​Для определения шага цикла​For … Next​

​200?’200px’:»+(this.scrollHeight+5)+’px’);»>if e>=1 then exit​

​: Правила надо читать,​​и есть массив,​ | A​
​ = 1 To​

​ sheet = (Excel.Worksheet)excelappworkbook.ActiveSheet;​ сделать цикл по​ ‘ … Next​ будет 64 значения,​
​ | 1| a|​ почти максимально) число​ Integer, m_end As​ не пуста.​ 1 Loop End​

​ то цикл прерывается:​​ в VBA можно​или как цикл​
​ for(do)​ там всё написано.​ где хранятся символа.​1 | ………..​ 2 Sheets(i).Visible =​ label24.Text = sheet.Cells[2,​ столбцам Excel файла.​ cНет, это не​ в B1=32, C1=64,​ X |​ в Excel.​ Integer)​Однако, как было показано​
​ Sub​For i =​ использовать отрицательную величину,​For Each​Только какое отношение​BOOM​ табл.2: 1. наименование​ | A​
​ False Next i​ 2].ToString();результат: System._ComObject​ Надо в первой​ подходит. Он просто​ D1=16.​|2 | B​

​не найдя данное​​For i =​

planetaexcel.ru

Построить формулу с циклом для перебора вариантов сочетаний. (Формулы/Formulas)

​ в примерах цикла​​В приведённом примере условие​
​ 1 To 100​ например, вот так:​.​
​ вопрос имеет к​: я сделал через​
​ 2. символ​2 | Подгруппа​ End Sub​mih0505​ строке отыскать столбец​ работает с выделеным​Знаю, что на​ | 2| b|​ число, или число​ m_start To m_end​Do While​iFib_Next < 1000​ If dValues(i) =​
​For i =​Цикл​ теме? Циклы имеются​ функцию ВПР​Вопрос, как можно​
​ B |​
​Пример №3:​: C# sheet.Cells[2, 2].Value.ToString();​ с нужным числом.​ диапазоном. А мне​
​ лист весь вывод​
​ Y |​
​ больше данного, формула​
​CYCLE = CYCLE​
​, в некоторых ситуациях​проверяется в начале​ dVal Then IndexVal​
​ 10 To 1​For … Next​ в большинстве программ,​
​0mega​ макросом проставить правильные​1 | товар1​
​Рассмотрим вариант цикла​Цикл​Вопрос становиться все​
​ нужно чтобы он​ не поместится, поэтому,​|3 | C​
​ возвращает значение из​
​ + i​ нужно, чтобы цикл​ цикла. Поэтому если​
​ = i Exit​
​ Step -1 iArray(i)​
​использует переменную, которая​
​ это не повод​
​:​
​ символа в таблицу​
​ | B​
​ с Step (шагом)​
​For…Next​
​ актуальнее! Неужели нельзя​
​ проверял условие в​
​ либо буду использовать​
​ | _| c|​
​ последней заполненной ячейки​
​Next​
​ был выполнен хотя​ бы первое значение​ For End If​ = i Next​ последовательно принимает значения​ постить в темы​Гость​
​ 1 из таблицы​
​1 | товар5​
​ через одну ячейку,​используется когда необходимо​ запустить цикл по​
​ каждой строке от​ в колонке A1​ Z |​
​alexfa88​End Function​ бы один раз,​
​iFib_Next​ Next i​ i​
​ из заданного диапазона.​ с циклами вопросы​,​
​ 2, если она​
​ | B​ в данном случае​ повторить действия заранее​ столбца Excel?​
​ 1 до 100.Ну​ каждый раз по​|4 | D​: есть правда один​суммирует в цикле​ не зависимо от​было бы больше​Цикл​Здесь шаг приращения равен​ С каждой сменой​
​ хоть как-то с​никак я могу​ не постоянна, имеет​1 | ……..​ будут заполнены ячейки​
​ заданное кол-во раз.​Петррр​ так какие проблемы,​ 2 значения (получится​ | _| d|​ нюанс:​ все целые в​ первоначального результата условного​ 1000, то цикл​Do While​-1​ значения переменной выполняются​ ними связанные.​ войти в тему​ разное кол-во наименований?​
​ | B​
​ через одну (А1,А3,А5,А7,А9).​Цикл​
​: Собственно, в чем​ вставь проверку условия​
​ как раз 65536),​

​ _ |​если в одном​ диапазоне от m_start​ выражения. В таком​
​ бы не выполнялся​выполняет блок кода​, поэтому переменная​ действия, заключённые в​

​savrix​​ …​0mega​2 | Подгруппа​
​ Sub example3 ()​For…Nex​ проблема?​
​ в том цикле,​
​ либо попрошу опять​
​|5 | E​
​ квартале лимит не​ до m_end включительно.​ случае условное выражение​ ни разу.​
​ до тех пор,​

​i​​ теле цикла. Это​
​: Доброго времени суток!!!​предложенный вариант выполняет​:​ С |​ Dim i As​t имеет следующий синтаксис:​piloterist​
​ который написал Comanche.​ же здесь помощи,​

​ | _| _|​​ устанавливался вовсе (такое​
​alexfa88​ нужно поместить в​Другой способ реализовать цикл​ пока выполняется заданное​
​с каждым повторением​
​ легко понять из​

excelworld.ru

Как создать цикл перебирающий значения клеток в Excel?

​ Господа, подскажите пожалуйста​​ эти требования .​BOOM​1 | товар1​

​ Long For i​
​For i = Start​: ну столбец же​ А если не​ чтобы реализовать переход​ _ |​ тоже может быть),​: Доброго времени суток!​ конце цикла, вот​Do While​ условие. Далее приведён​ цикла принимает значения​ простого примера:​ такой вопрос… Есть​Quote​, здравствуйте​ | С​ = 1 To​ To End [Step​ в Excel имеет​ подходит то опиши​ на другой лист​———————​ но при этом​
​Есть следующая задача:​ так:​
​– поместить условие​ пример процедуры​ 10, 9, 8,​For i =​ табличка, подобие ЗП,​(Гость)200?’200px’:»+(this.scrollHeight+5)+’px’);»>…пользователь получил таблицу​наличие настоящей таблицы​1 | товар2​ 10 Step 2​ StepSize]​ буквенное обозначение… как​

CyberForum.ru

Как сделать цикл в Excel

​ задачу, может какие​ с помощью такого​Хочу в итоговой​ лимит был в​существует ряд предприятий,​Do … Loop​ не в начале,​Sub​ … 1.​ 1 To 10​ и нужно что​ из 2000 строк​ в формате​
​ | С​ ActiveSheet.Range(«A» & i).Value​

​//операторы//​​ мне прогнать цикл​ другие варианты есть.Почти​ макроса (вычитал на​ колонке получить массив​ предыдущем квартале, то​ по которым в​ Until IsEmpty(Cells(iRow, 1))​ а в конце​, в которой при​Цикл​ Total = Total​ бы на отдельных​ или 20, скопировал​.xls​1 | ………​ = i Next​Next [i]​ с буквы А​

​ получилось, он пербирает​​ одном из форумов):​ данных:​ =ПРОСМОТР(9E+307;$D4:W4) вытянет просто​

Цикл по столбцам Excel Файла

​ начале квартала устанавливается​​Урок подготовлен для Вас​
​ цикла. В этом​ помощи цикла​For Each​ + iArray(i) Next​ листах формировались расчетные​ ее на этот​
​- существенно ускорит​ | С​ i End Sub​i​

​ например на 100​​ значения, Но у​200?’200px’:»+(this.scrollHeight+5)+’px’);»>set ws = activesheet​

​1 A1aX​​ самое последнее значение​ лимит задолженности, потом​ командой сайта office-guru.ru​ случае цикл будет​Do While​похож на цикл​ i​ листки, по каждому​ лист…​ вероятность правильного ответа​Я попробовала через​

​Balbasochka​​– численная переменная VBA​ столбцов вперед чтобы​

​ меня следубщая задача:​​If ws.cols.count =​2 A1aY​ из всего массива,​ в течение квартала​Источник: http://www.excelfunctions.net/VBA-Loops.html​ выполнен хотя бы​выводятся последовательно числа​For … Next​В этом простом цикле​

​ сотруднику, которые есть​​Во вторую таблицу​ .​=ЕСЛИ(И(A37=1;СМЕЩ(A37;-1;0;;1)=2);ПРАВСИМВ(СМЕЩ(A37;-1;1;1);1);ЕСЛИ(И(A37=1;СМЕЩ(A37;-2;0;;1)=2);ПРАВСИМВ(СМЕЩ(A37;-2;1;1);1);ЕСЛИ(И(A37=1;СМЕЩ(A37;-3;0;;1)=2);ПРАВСИМВ(СМЕЩ(A37;-3;1;1);1);ЕСЛИ(И(A37=1;СМЕЩ(A37;-4;0;;1)=2);ПРАВСИМВ(СМЕЩ(A37;-4;1;1);1);ЕСЛИ(И(A37=1;СМЕЩ(A37;-5;0;;1)=2);ПРАВСИМВ(СМЕЩ(A37;-5;1;1);1);ЕСЛИ(И(A37=1;СМЕЩ(A37;-6;0;;1)=2);ПРАВСИМВ(СМЕЩ(A37;-6;1;1);1);ЕСЛИ(И(A37=1;СМЕЩ(A37;-7;0;;1)=2);ПРАВСИМВ(СМЕЩ(A37;-7;1;1);1);»»)))))))​: Добрый день!​ (счетчик)​ найти столбцы, у​Есть клетка A1,​ 65… then​3 A1aZ​ а не то​ эти лимиты могут​Перевел: Антон Андронов​ раз, не зависимо​ Фибоначчи не превышающие​, но вместо того,​

​For … Next​​ в табличке. Записать​ можно вводить данные​P.S.​Но строк может​
​Помогите, пожалуйста, с​
​Start​ который в i-ой​ D1 и E1.​set ws =​4 A1bX​ что было именно​ пересматриваться, частота и​Автор: Антон Андронов​ от того, выполняется​ 1000:​ чтобы перебирать последовательность​используется переменная​ макрос с созданием​ с клавиатуры, а​если не угадал,​ быть очень много…​ формулой.​– численное выражение, определяет​

​ строке нужные мне​​Если значение A1​

CyberForum.ru

Цикл For…Next

​ activeworkbook.sheets.add​​5 A1bY​​ в конкретном квартале.​ периодичность пересмотров не​Ampersand​
​ ли условие.​​’Процедура Sub выводит​​ значений для переменной-счётчика,​
​i​ этого листка для​ можно через copy-paste.​
​ тогда файл в​
​ можно задать какой-то​

​Есть таблица с​
​ начальное значение для​ данные.​
​ Как сделать?For i​
​end if​…​В принципе это​
​ устанавливаются, т.е. могут​
​: ЦИКЛИЧЕСКИЕ ФОРМУЛЫ​Схематично такой цикл​ числа Фибоначчи, не​
​ цикл​, которая последовательно принимает​ каждого сотрудника и​Quote​ студию​ цикл? Если ЛОЖЬ,​ определенной структурой.​ переменной​Петррр​ = 1 To​Буду благодарен если​12 A1dZ​ я уже начинаю​ пересматривать часто в​Чтобы формулы работали​Do While​ превышающие 1000 Sub​For Each​ значения 1, 2,​ прописать туда ссылки​(Гость)200?’200px’:»+(this.scrollHeight+5)+’px’);»>… нажал на​RAN​ то минус 1​Нужно определить для​
​End​
​: Можно и по​ 100 If Cells(i,​ поможете реализовать идею,​13 A2aX​ умничать и придираться,​
​ одном квартале, в​ в цикле -​с проверяемым условием​ Fibonacci() Dim i​выполняет набор действий​ 3, … 10,​ на нужные ячейки​ кнопку и символа​​:​
​ строка к предыдущему​ каждой позиции подгруппу,​– это также численное​ индексам обращаться.​ 1) < 10​ и объяснить принцип​…​ для решения данной​ другом квартале может​ должны быть включены​​ в конце будет​
​ As Integer ‘счётчик​ для каждого объекта​ и для каждого​ с общей таблицы​ поставились бы…​BOOM​ и т.д.​ в которую она​ выражение, определяет конечное​piloterist​ Then Cells(i, 4)​ действия конкретного макроса.​24 A2dZ​ проблемы можно вручную​

excelworld.ru

Цикл в формуле — проверка условий и подстановка значений (Формулы/Formulas)

​ обойтись вообще без​​ итерации.​
​ выглядеть вот так:​ для обозначения позиции​
​ из указанной группы​ из этих значений​
​ не проблема… НО​Символы займут нужное​или не​VBA совсем не​ входит. Код уровня​ значение для переменной.​: По каким индексам?​ = Cells(i, 1)​Прикрепил сам файл​25 B1aX​ изменить диапазон массива,​ пересмотров.​Ячейка выполняет действия​Do … Loop​
​ элемента в последовательности​
​ объектов. В следующем​ выполняется код VBA,​ делать это для​
​ место автоматически сразу​BOOM​
​ знаю. Помогите, пожалуйста!​ для наименования подгруппы​
​Цикл по счетчику​ Задача пройтись циклом​
​ Else Cells(i, 5)​ с задачей, а​
​…​ что не так​
​Каким образом можно​ со своими же​
​ While iFib_Next <​ Dim iFib As​
​ примере при помощи​
​ находящийся внутри цикла.​ каждого сотрудника долго((((…​
​ после ввода таблицы​отвечать на вопрос,​
​_Boroda_​ всегда один и​
​ выделяется ключевыми словами​
​ по первой строке​
​ = Cells(i, 1)​ то строки таблицы​…​
​ долго,​ на определенный срез​
​ значеними​ 1000​
​ Integer ‘хранит текущее​ цикла​
​ Таким образом, данный​ Так вот суть​
​А кнопочка-то зачем​ зависит от вас.​
​: Так пойдет?​ тот же, код​
​ For и Next.​ всех столбцов и​
​ End If Next​ съезжают…​
​120 E2dZ​но если в​
​ (например на последний​В ячейку D2​
​Цикл​ значение последовательности Dim​
​For Each​ цикл суммирует элементы​
​ вопроса… Подскажите, как​​ нужна ?​
​0mega​=ЕСЛИ(A20=2;ПСТР(B20;11;99);C19)​ уровня для номенклатуры​ После начального For​ отобрать столбцы прошедшие​ i​Светлый​
​Конец.​ формулу еще заложить​

​ день квартала) в​​ вволите значение и​
​Do Until​
​ iFib_Next As Integer​выполняется перечисление всех​
​ массива​

​ сделать цикл, что​​BOOM​принципиальный противник макросов,​Или так (если​ тоже всегда один​
​ указывается имя переменной,​ по условию. А​Задача есть 2 формулы​: Макросы (VBA) в​Для упрощения решения​
​ механизм просмотра массива​ одном столбце сразу​ ячейка A2 сама​очень похож на​ ‘хранит следующее значение​

​ листов в текущей​​iArray​ бы он проходил​
​: просто задачу такую​
​ так что его​ с пропусками)​ и тот-же. Количество​ данная переменная (i)​ потом у этих​ 1 в первую​ другом разделе. Или​

excelworld.ru

цикл (цикл)

​ могу предложить добавить​​ по определенному критерию,​ подтянуть все самые​
​ себя пересчитывает​ цикл​ последовательности Dim iStep​ рабочей книге Excel:​в переменной​
​ по всей табличке​ поставили . Т.к​ ответ либо не​Код=ЕСЛИ(A20=2;»»;ЕСЛИ(A19=2;ПСТР(B19;11;99);D19))​
​ строк в каждой​ будет счетчиком, после​ столбцов получить значение​ подставляется число X.​
​ переименуйте тему.​ в каждый исходный​ то это будет​ последние пересмотренные лимиты?​B2=ABS(B2-D2)​Do While​ As Integer ‘хранит​

​Dim wSheet As​​Total​​ и для каждого​​ пользователи не умеют​
​ удовлетворяет постановке задачи​Balbasochka​​ подгруппе неопределенное, количество​​ знака равенства идёт​ в определенной строке.​ В конце расчёта​
​А формульное решение​
​ столбец количество символов​ очень замечательно! :)​Прилагаю файл, в​

​В ячейку А1​​: блок кода в​​ размер следующего приращения​​ Worksheet For Each​​.​​ сотрудника создавал расчетный​ пользоваться офисом и​
​либо вы поставили​​: Не работает, возможно​ подгрупп тоже может​ начальное значение счетчика,​Петррр​
​ получаем число X​ Вашей задачи во​
​ для равного значения​kim​ нем же есть​sad

​ вводим любую информацию​​ теле цикла выполняется​ ‘инициализируем переменные i​ wSheet in Worksheets​В приведённом выше примере​
​ листок. Пример файла​ чтобы им меньше​ задачу неверно.​
​ я описала в​ отличаться.​

​ а после ключевого​​: C# using System;​
​ но другое. Теперь​ вложенном файле.​ строк в каждом​: =ЕСЛИОШИБКА(ПРОСМОТР(2;1/((X2=$D$2:$W$2)*($D4:$W4<>»»));$D4:W4);»»)​ предложение, какой именно​Автоматически в В1​ раз за разом​ и iFib_Next i​ MsgBox «Найден лист:​ шаг приращения цикла​ прилагаю. Заранее благодарен​ делать манипуляций, хотят​На форум иногда​ тексте не очень​Имеем:​ слова To -​ using Exel =​ надо подставить это​200?’200px’:»+(this.scrollHeight+5)+’px’);»>=СМЕЩ(A$1;ОТБР((СТРОКА()-1)/32/64/16);)&СМЕЩ(B$1;ОСТАТ(ОТБР((СТРОКА()-1)/64/16);32);)&СМЕЩ(C$1;ОСТАТ(ОТБР((СТРОКА()-1)/16);64);)&СМЕЩ(D$1;ОСТАТ(СТРОКА()-1;16);)​

​ столбце:​​Yurasha​ цикл нужно использовать,​

​ зафиксируется время​​ до тех пор,​ = 1 iFib_Next​

​ » & wSheet.Name​​ не указан, поэтому​​ за любую помощь.​​ одной кнопочкой.​
​ заглядывают экстрасенсы, но​ точно.​Код уровня группы​
​ конечное значение счетчика.​ Microsoft.Office.Interop.Excel; class Program​
​ число в начало​​И универсальная:​| | A1|B1|C1|D1|​: Здравствуйте!​ но, к сожалению​Интересное решение предложил​
​ пока заданное условие​ = 0 ‘цикл​ Next wSheet​ для пошагового увеличения​
​ Всем добра )​​я могу проставить​ не часто…​В ячейку C​
​ | Наименование |​ По умолчанию счётчик​ { static void​
​ и так до​Код200?’200px’:»+(this.scrollHeight+5)+’px’);»>=СМЕЩ(A$1;ОСТАТ(ОТБР((СТРОКА()-1)/СЧЁТЗ(B:B)/СЧЁТЗ(C:C)/СЧЁТЗ(D:D));СЧЁТЗ(A:A));)&СМЕЩ(B$1;ОСТАТ(ОТБР((СТРОКА()-1)/СЧЁТЗ(C:C)/СЧЁТЗ(D:D));СЧЁТЗ(B:B));)&СМЕЩ(C$1;ОСТАТ(ОТБР((СТРОКА()-1)/СЧЁТЗ(D:D));СЧЁТЗ(C:C));)&СМЕЩ(D$1;ОСТАТ(СТРОКА()-1;СЧЁТЗ(D:D));)​

​|——————-​​Я здесь новичок​ не догадываюсь, как​ Michael_S​ выполняется (результат условного​ Do While будет​Оператор​ переменной​
​Udik​ в цикле только​0mega​ нужно проставить значение​ Подгруппа​ работает с шагом​

​ Main(string[] args) {​​ тех пор пока​
​А эту формулу​
​|1 | A​ и это мой​
​ его реализовать в​Но этот способ​
​ выражения равен​
​ выполняться до тех​
​Exit For​

​i​​: Лучше вам новую​ значение, типа символа​: Все мало-мальски имеющие​

​ из столбца B​​2 | Подгруппа​ равным единице. Можно​ Exel.Application app =​ верхнее и нижнее​ можно протянуть по​ | 1| a|​ первый пост.​ одной формуле.​ требует дополнителный столбец​True​

​ пор, пока значение​​применяется для прерывания​​от 1 до​ тему открыть, типа​
​ или слова, а​ эти возможности сейчас​ и его надо​ A |​ задавать другое значение​ new Microsoft.Office.Interop.Excel.Application(); app.Workbooks.Add(Type.Missing);​ значения X не​ столбцам и получим​ X |​

​Помогите пожалуйста составить​​Пожалуйста, если есть​ (который можно закрыть​). В следующей процедуре​ ‘текущего числа Фибоначчи​ цикла. Как только​ 10 по умолчанию​добавление новых листов по​ вот как формулу​ участвуют на съемках​ найти снизу вверх.​1 | товар1​ (StepSize), на которое​ Exel.Worksheet sheet =​ совпадут.​ все 64*32*64*16 сочетаний:​|2 | B​ цикл.​ какие либо варианты​ или расположить на​Sub​ не превысит 1000​ в коде встречается​ используется приращение​ списку​ проставлять не знаю​ TV​Если была бы​ |​ будет изменяться «i»,​ (Exel.Worksheet)app.ActiveSheet; for (int​

​Как это сделать​​Код200?’200px’:»+(this.scrollHeight+5)+’px’);»>=СМЕЩ($A$1;ОТБР(((СТРОКА()-1)+(СТОЛБЕЦ(A1)-1)*65536)/32/64/16);)&СМЕЩ($B$1;ОСТАТ(ОТБР(((СТРОКА()-1)+(СТОЛБЕЦ(A1)-1)*65536)/64/16);32);)&СМЕЩ($C$1;ОСТАТ(ОТБР(((СТРОКА()-1)+(СТОЛБЕЦ(A1)-1)*65536)/16);64);)&СМЕЩ($D$1;ОСТАТ(СТРОКА()-1;16);)​ | 2| b|​​Думаю, что правильнее​ — помогите пожалуйста,​

excelworld.ru

​ «далеких » адресах.​

To get the most out of Excel and VBA, you need to know how to use loops efficiently.

In VBA, loops allow you to go through a set of objects/values and analyze it one by one. You can also perform specific tasks for each loop.

Here is a simple example of using VBA loops in Excel.

Suppose you have a dataset and you want to highlight all the cells in even rows. You can use a VBA loop to go through the range and analyze each cell row number. If it turns out to be even, you give it a color, else you leave it as is.

Now this, of course, is very simple of looping in Excel VBA (and you can also do this using conditional formatting).

In real life, you can do a lot more with VBA loops in Excel that can help you automate tasks.

Here are some more practical examples where VBA loops can be useful:

  • Looping through a range of cells and analyzing each cell (highlight cells with a specific text in it).
  • Looping through all the worksheets and do something with each (such as protect/unprotect it).
  • Loop through all the open workbooks (and save each workbook or close all except the active workbook).
  • Loop through all the characters in a cell (and extract the numeric part from a string).
  • Loop through all the values an array.
  • Loop through all the charts/objects (and give a border or change the background color).

Now to best use loops in Excel VBA, you need to know about the different kinds that exist and the correct syntax of each.

Using Loops in Excel VBA - The Ultimate Guide

In this tutorial, I’ll showcase different types of Excel VBA loops and cover a few examples for each loop

Note: This is going to be a huge tutorial, where I will try and cover each VBA loop in some detail. I recommend you bookmark this page for future reference.

If you’re interested in learning VBA the easy way, check out my Online Excel VBA Training.

For Next Loop

The ‘For Next’ loop allows you to go through a block of code for the specified number of times.

For example, if I ask you to add the integers from 1 to 10 manually, you would add the first two numbers, then add the third number to the result, then add the fourth number to the result, as so on..

Isn’t it?

The same logic is used in the For Next loop in VBA.

You specify how many times you want the loop to run and also specify what you want the code to do each time the loop is run.

Below is the syntax of the For Next loop:

For Counter = Start To End [Step Value]
[Code Block to Execute]
Next [counter]

In the For Next loop, you can use a Counter (or any variable) that will be used to run the loop. This counter allows you to run this loop for a required number of times.

For example, if I want to add the first 10 positive integers, then my Counter value would be from 1 to 10.

Let’s have a look at a few examples to better understand how For Next loop works.

Example 1 – Adding the first 10 positive integers

Below is the code that will add the first 10 positive integers using a For Next loop.

It will then display a message box showing the sum of these numbers.

Sub AddNumbers()
Dim Total As Integer
Dim Count As Integer
Total = 0
For Count = 1 To 10
Total = Total + Count
Next Count
MsgBox Total
End Sub

In this code, the value of Total is set to 0 before getting into the For Next loop.

Once it gets into the loop, it holds the total value after every loop. So after the first loop, when Counter is 1, ‘Total’ value becomes 1, and after the second loop it becomes 3 (1+2), and so on.

And finally, when the loop ends, ‘Total’ variable has the sum of the first 10 positive integers.

A MsgBox then simply displays the result in a message box.

Example 2 – Adding the first 5 Even Positive Integers

To sum the first five even positive integers (i.e, 2,4,6,8, and 10), you need a similar code with a condition to only consider the even numbers and ignore the odd numbers.

Here is a code that will do it:

Sub AddEvenNumbers()
Dim Total As Integer
Dim Count As Integer
Total = 0
For Count = 2 To 10 Step 2
Total = Total + Count
Next Count
MsgBox Total
End Sub

Note that we started the Count value from 2 and also used ‘Step 2‘.

When you use ‘Step 2’, it tells the code to increment the ‘Count’ value by 2 every time the loop is run.

So the Count value starts from 2 and then becomes 4, 6, 8 and 10 as the looping occurs.

NOTE: Another way of doing this could be to run the loop from 1 to 10 and within the loop check whether the number is even or odd. However, using Step, in this case, is a more efficient way as it does not require the loop to run 10 times, but only 5 times.

The Step value can also be negative. In such as case, the Counter starts at a higher value and keeps getting decremented by the specified Step value.

Example 3 – Entering Serial Number in the Selected Cells

You can also use the For Next loop to go through a collection of objects (such as cells or worksheets or workbooks),

Here is an example that quickly enters serial numbers in all the selected cells.

Sub EnterSerialNumber()
Dim Rng As Range
Dim Counter As Integer
Dim RowCount As Integer
Set Rng = Selection
RowCount = Rng.Rows.Count
For Counter = 1 To RowCount
ActiveCell.Offset(Counter - 1, 0).Value = Counter
Next Counter
End Sub

The above code first counts the number of selected rows and then assigns this value to the variable RowCount. We then run the loop from ‘1 to RowCount’.

Also note that since selection can be any number of rows, we have Set the variable Rng to Selection (with the line ‘Set Rng = Selection’). Now we can use the ‘Rng’ variable to refer to the selection in our code.

Example 4 – Protect All Worksheets in the Active Workbook

You can use the ‘For Next’ loop to go through all the worksheets in the active workbook, and protect (or unprotect) each of the worksheets.

Below is the code that will do this:

Sub ProtectWorksheets()
Dim i As Integer
For i = 1 To ActiveWorkbook.Worksheets.Count
Worksheets(i).Protect
Next i
End Sub

The above code counts the number of sheets by using ActiveWorkbook.Worksheets.Count. This tells VBA how many times the loop needs to be run.

In each instance, it refers to the Ith workbook (using Worksheets(i)) and protects it.

You can use this same code to Unprotect worksheets too. Just change the line Worksheets(i).Protect to Worksheets(i).UnProtect.

Nested ‘For Next’ Loops

You can use nested ‘For Next’ loops to get more complex automation done in Excel. A nested ‘For Next’ loop would mean that there is a ‘For Next’ loop within a ‘For Next’ loop.

Let me show you how to use this using an example.

Suppose I have 5 workbooks open in my system and I want to protect all the worksheets in all these workbooks.

Below is the code that will do this:

Sub ProtectWorksheets()
Dim i As Integer
Dim j As Integer
For i = 1 To Workbooks.Count
For j = 1 To Workbooks(i).Worksheets.Count
Workbooks(i).Worksheets(j).Protect
Next j
Next i
End Sub

The above is a nested For Next loop as we have used one For Next loop within another.

‘EXIT For’ Statements in For Next Loops

‘Exit For’ statement allows you to exit the ‘For Next’ loop completely.

You can use it in cases where you want the For Next loop to end when a certain condition is met.

Let’s take an example where you have a set of numbers in Column A and you want to highlight all the negative numbers in red font. In this case, we need to analyze each cell for its value and then change the font color accordingly.

But to make the code more efficient, we can first check if there are any negative values in the list or not. If there are no negative values, we can use the Exit For the statement to simply come out of the code.

Below is the code that does this:

Sub HghlightNegative()
Dim Rng As Range
Set Rng = Range("A1", Range("A1").End(xlDown))
Counter = Rng.Count
For i = 1 To Counter
If WorksheetFunction.Min(Rng) >= 0 Then Exit For
If Rng(i).Value < 0 Then Rng(i).Font.Color = vbRed
Next i
End Sub

When you use the ‘Exit For’ statement within a nested ‘For Next’ loop, it will come out of the loop in which it is executed and go on to execute the next line in the code after the For Next loop.

For example, in the below code, the ‘Exit For’ statement will get you out of the inner loop, but the outer loop would continue to work.

Sub SampleCode()
For i = 1 To 10
For j = 1 to 10
Exit For
Next J
Next i
End Sub

Do While Loop

A ‘Do While’ loop allows you to check for a condition and run the loop while that condition is met (or is TRUE).

There are two types of syntax in the Do While Loop.

Do [While condition]
[Code block to Execute]
Loop

and

Do
[Code block to Execute]
Loop [While condition]

The difference between these two is that in the first, the While condition is checked first before any code block is executed, and in the second case, the code block is executed first and then the While condition is checked.

This means that if the While condition is False is both the cases, the code will still run at least once in the second case (as the ‘While’ condition is checked after the code has been executed once).

Now let’s see some examples of using Do While loops in VBA.

Example 1 – Add First 10 Positive Integers using VBA

Suppose you want to add the first ten positive integers using the Do While loop in VBA.

To do this, you can use the Do While loop until the next number is less than or equal to 10. As soon as the number is greater than 1o, your loop would stop.

Here is the VBA code that will run this Do While loop and the show the result in a message box.

Sub AddFirst10PositiveIntegers()
Dim i As Integer
i = 1
Do While i <= 10
Result = Result + i
i = i + 1
Loop
MsgBox Result
End Sub

The above loop continues to work until the value of ‘i’ becomes 11. As soon as it becomes 11, the loop ends (as the While condition becomes False).

Within the loop, we have used a Result variable that holds the final value Once the loop is completed, a message box shows the value of the ‘Result’ variable.

Example 2 –  Enter Dates For the Current Month

Let’s say you want to enter all the dates of the current month into a worksheet column.

You can do that by using the following Do While loop code:

Sub EnterCurrentMonthDates()
Dim CMDate As Date
Dim i As Integer
i = 0
CMDate = DateSerial(Year(Date), Month(Date), 1)
Do While Month(CMDate) = Month(Date)
Range("A1").Offset(i, 0) = CMDate
i = i + 1
CMDate = CMDate + 1
Loop
End Sub

The above code would enter all the dates in the first column of the worksheet (starting from A1). The loops continue till the Month value of the variable ‘CMDate’ matches that of the current month.

Exit Do Statement

You can use the Exit Do statement to come out of the loop. As soon as the code executes the ‘Exit Do’ line, it comes out of the Do While loop and passes the control to the next line right after the loop.

For example, if you want to enter the first 10 dates only, then you can exit the loop as soon as the first 10 dates are entered.

The below code will do this:

Sub EnterCurrentMonthDates()
Dim CMDate As Date
Dim i As Integer
i = 0
CMDate = DateSerial(Year(Date), Month(Date), 1)
Do While Month(CMDate) = Month(Date)
Range("A1").Offset(i, 0) = CMDate
i = i + 1
If i >= 10 Then Exit Do
CMDate = CMDate + 1
Loop
End Sub

In the above code, the IF statement is used to check if the value of i is greater than 10 or not. As soon as the value of ‘i’ becomes 10, Exit Do statement is executed and the loop ends.

Do Until Loop

‘Do Until’ loops are very much like the ‘Do While’ loops.

In ‘Do While’, the loop runs till the given condition is met, while in ‘Do Until’, it loops until the specified condition is met.

There are two types of syntax in the Do Until Loop.

Do [Until condition]
[Code block to Execute]
Loop

and

Do
[Code block to Execute]
Loop [Until condition]

The difference between these two is that in the first, the Until condition is checked first before any code block is executed, and in the second case, the code block is executed first and then the Until condition is checked.

This means that if the Until condition is TRUE is both cases, the code will still run at least once in the second case (as the ‘Until’ condition is checked after the code has been executed once).

Now let’s see some examples of using Do Until loops in VBA.

Note: All the examples for Do Until are the same as that of Do While. These have been modified to show you how the Do Until loop works.

Example 1 – Add First 10 Positive Integers using VBA

Suppose you want to add the first ten positive integers using the Do Until loop in VBA.

To do this, you need to run the loop until the next number is less than or equal to 10. As soon as the number is greater than 1o, your loop would stop.

Here is the VBA code that will run this loop and show the result in a message box.

Sub AddFirst10PositiveIntegers()
Dim i As Integer
i = 1
Do Until i > 10
Result = Result + i
i = i + 1
Loop
MsgBox Result
End Sub

The above loop continues to work until the value of ‘i’ becomes 11. As soon as it becomes 11, the loop ends (as the ‘Until’ condition becomes True).

Example 2 –  Enter Dates For the Current Month

Let’s say you want to enter all the dates of the current month into a worksheet column.

You can do that by using the following Do Until loop code:

Sub EnterCurrentMonthDates()
Dim CMDate As Date
Dim i As Integer
i = 0
CMDate = DateSerial(Year(Date), Month(Date), 1)
Do Until Month(CMDate) <> Month(Date)
Range("A1").Offset(i, 0) = CMDate
i = i + 1
CMDate = CMDate + 1
Loop
End Sub

The above code would enter all the dates in the first column of the worksheet (starting from A1). The loop continues until the Month of variable CMDate is not equal to that of the current month.

Exit Do Statement

You can use the ‘Exit Do’ statement to come out of the loop.

As soon as the code executes the ‘Exit Do’ line, it comes out of the Do Until loop and passes the control to the next line right after the loop.

For example, if you want to enter the first 10 dates only, then you can exit the loop as soon as the first 10 dates are entered.

The below code will do this:

Sub EnterCurrentMonthDates()
Dim CMDate As Date
Dim i As Integer
i = 0
CMDate = DateSerial(Year(Date), Month(Date), 1)
Do Until Month(CMDate) <> Month(Date)
Range("A1").Offset(i, 0) = CMDate
i = i + 1
If i >= 10 Then Exit Do
CMDate = CMDate + 1
Loop
End Sub

In the above code, as soon as the value of ‘i’ becomes 10, Exit Do statment is executed and the loop ends.

For Each

In VBA, you can loop through a set of collections using the ‘For Each’ loop.

Here are some examples of collections in Excel VBA:

  • A collection of all the open Workbooks.
  • A collection of all worksheets in a workbook.
  • A collection of all the cells in a range of selected cells.
  • A collection of all the charts or shapes in the workbook.

Using the ‘For Each’ loop, you can go through each of the objects in a collection and perform some action on it.

For example, you can go through all the worksheets in a workbook and protect these, or you can go through all the cells in the selection and change the formatting.

With the ‘For Each’ loop (also referred to as the ‘For Each-Next’ loop), you don’t need to know how many objects are there in a collection.

‘For Each’ loop would automatically go through each object and perform the specified action. For example, if you want to protect all the worksheets in a workbook, the code would be the same whether you have a workbook with 3 worksheets or 30 worksheets.

Here is the syntax of For Each-Next loop in Excel VBA.

For Each element In collection
[Code Block to Execute]
Next [element]

Now let’s see a couple of examples of using the For Each Loop in Excel.

Example 1 – Go through All the Worksheets in a Workbook (and Protect it)

Suppose you have a workbook where you want to protect all the worksheets.

Below For Each-Next loop can do this easily:

Sub ProtectSheets()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Protect
Next ws
End Sub

In the above code, we have defined ‘ws’ variable as a Worksheet object. This tells VBA that ‘ws’ should be interpreted as a worksheet object in the code.

Now we use the ‘For Each’ statement to go through each ‘ws’ (which is a worksheet object) in the collection of all the worksheets in the active workbook (given by ActiveWorkbook.Worksheets).

Note that unlike other loops where we have tried to protect all the worksheets in a workbook, here we don’t need to worry about how many worksheets are there in the workbook.

We don’t need to count these to run the loop. For Each loop ensures that all the objects are analyzed one by one.

Example 2 – Go through All the Open Workbooks (and Save All)

If you work with multiple workbooks at the same time, it can come in handy to be able to save all these workbooks at once.

Below VBA code can do this for us:

Sub SaveAllWorkbooks()
Dim wb As Workbook
For Each wb In Workbooks
wb.Save
Next wb
End Sub

Note that in this code, you don’t get a prompt that asks you to save the workbook in a specific location (if saving it for the first time).

It saves it in the default folder (it was the ‘Documents’ folder in my case). This code works best when these files are already saved and you’re making changes and you want to save all the workbooks quickly.

Example 3 – Go through All the Cells in a Selection (Highlight negative values)

Using the ‘For Each’ loop, you can loop through all the cells in a specific range or in the selected range.

This can be helpful when you want to analyze each cell and perform an action based on it.

For example, below is the code that will go through all the cells in the selection and change the cell color of the cells with negative values to red.

Sub HighlightNegativeCells()
Dim Cll As Range
For Each Cll In Selection
If Cll.Value < 0 Then
Cll.Interior.Color = vbRed
End If
Next Cll
End Sub

(Note I’ve used Cll as a short variable name for Cell. It’s advisable not to use object names such as Sheets or Range as variable names)

In the above code, the For Each-Next loop goes through the collection of cells in the selection. IF statement is used to identify if the cell value is negative or not. In case it is, the cell is given a red interior color, else it goes to the next cell.

In case you don’t have a selection, and instead want VBA to select all the filled cells in a column, starting from a specific cell (just like we use Control + Shift + Down arrow key to select all filled cells), you can use the below code:

Sub HighlightNegativeCells()
Dim Cll As Range
Dim Rng As Range
Set Rng = Range("A1", Range("A1").End(xlDown))
For Each Cll In Rng
If Cll.Value < 0 Then
Cll.Interior.Color = vbRed
End If
Next Cll
End Sub

In the above example, it doesn’t matter how many filled cells are there. It will start from cell A1 and analyze all the contiguous filled cells in the column.

You also don’t need to have cell A1 selected. You can have any far-off cell selected and when the code runs, it will still consider all the cells in column A (starting from A1) and color the negative cells.

‘Exit For’ Statment

You can use the ‘Exit For’ statement in the For Each-Next loop to come out of the loop. This is usually done in case a specific condition is met.

For example, in Example 3, as we are going through a set of cells, it can be more efficient to check if there are any negative values or not. In case there are no negative values, we can simply exit the loop and save some VBA processing time.

Below is the VBA code that will do this:

Sub HighlightNegativeCells()
Dim Cll As Range
For Each Cll In Selection
If WorksheetFunction.Min(Selection) >= 0 Then Exit For
If Cll.Value < 0 Then
Cll.Interior.Color = vbRed
End If
Next Cll
End Sub

Where to Put the VBA Code

Wondering where the VBA code goes in your Excel workbook?

Excel has a VBA backend called the VBA editor. You need to copy and paste the code in the VB Editor module code window.

Here are the steps to do this:

  1. Go to the Developer tab.IF Then Else in Excel VBA - Developer Tab in ribbon
  2. Click on the Visual Basic option. This will open the VB editor in the backend.Click on Visual Basic
  3. In the Project Explorer pane in the VB Editor, right-click on any object for the workbook in which you want to insert the code. If you don’t see the Project Explorer go to the View tab and click on Project Explorer.
  4. Go to Insert and click on Module. This will insert a module object for your workbook.VBA Loops - inserting module
  5. Copy and paste the code in the module window.VBA Loops - inserting module

You May Also Like the Following Excel Tutorials:

  • How to record a macro in Excel.
  • Creating User-defined functions in Excel.
  • Excel VBA Msgbox
  • How to Run a Macro in Excel.
  • How to Create and Use Add-ins in Excel.
  • Excel VBA Events – An Easy (and Complete) Guide.
  • How to Sort Data in Excel using VBA (A Step-by-Step Guide).
  • 24 Useful Excel Macro Examples for VBA Beginners (Ready-to-use).
  • How to Use Excel VBA InStr Function (with practical EXAMPLES).
  • Excel Personal Macro Workbook | Save & Use Macros in All Workbooks.
  • Using Select Case in Excel VBA.

This post provides a complete guide to the standard VBA For Loop and the VBA For Each Loop.

If you are looking for information about the VBA While and VBA Do Loop then go here.

If you want some quick info about the For loops then check out the Quick Guide table in the section below.

If you are looking for information on a particular topic then check out the Table of Contents below.

“History is about loops and continuums” – Mike Bidlo.
 

Related Links for the VBA For Loop

The Complete Guide to Ranges in Excel VBA.
The Complete Guide to Copying Data in Excel VBA.
VBA Do While Loop.

A Quick Guide to the VBA For Loop

Loop format Description Example
For … Next Run 10 times For i = 1 To 10
Next
For … Next Run 5 times. i=2,4, 6 etc. For i = 2 To 10 Step 2
Next
For … Next Run in reverse order For i = 10 To 1 Step -1
    Debug.Print i
Next
For … Next Go through Collection For i = 1 To coll.Count
    Debug.Print coll(i)
Next
For … Next Go through array For i = LBound(arr) To UBound(arr)
    Debug.Print arr(i)
Next i
For … Next Go through 2D array For i = LBound(arr) To UBound(arr)
    For j = LBound(arr,2) To UBound(arr,2)
        Debug.Print arr(i, j)
    Next j
Next i
For Each … Next Go through Collection Dim item As Variant
For Each item In coll
    Debug.Print item
Next item
For Each … Next Go through array Dim item As Variant
For Each item In arr
    Debug.Print item
Next item
For Each … Next Go through 2D array Dim item As Variant
For Each item In arr
    Debug.Print item
Next item
For Each … Next Go through Dictionary Dim key As Variant
For Each key In dict.Keys
    Debug.Print key, dict(key)
Next key
Both types Exit Loop For i = 1 To 10
    If Cells(i,1) = «found» Then
        Exit For
    End If
Next i

The VBA For Loop Webinar

If you are a member of the website, click on the image below to view the webinar for this post.

(Note: Website members have access to the full webinar archive.)

Introduction to the VBA For Loop

Loops are by far the most powerful component of VBA. They are the rocket fuel of your Macros. They can perform tasks in milliseconds that would take humans hours. They also dramatically reduce the lines of code your applications need.

For Loops have been part of all major programming languages since they were first used with Fortan in 1957.

If you have never used loops before then this post is a great place to start. It provides an in-depth guide to loops, written in plain English without the jargon.

Let’s start with a very important question – what are loops and why do we need them?

What are VBA For Loops?

A loop is simply a way of running the same lines of code a number of times. Obviously running the same code over and over would give the same result.

So what is important to understand is that the lines of code normally contain a variable that changes slightly each time the loop runs.

For example, a loop could write to cell A1, then cell A2, A3 and so on. The slight change each time is the row.

Let’s look at a simple example.

VBA For Loop Example 1

 
The following code  prints the values 1 to 5 in the Immediate Window(Ctrl + G to view).

Debug.Print 1
Debug.Print 2
Debug.Print 3
Debug.Print 4
Debug.Print 5

The Immediate Window

If you have not used the Immediate Window before then this section will get you up to speed quickly.

The function Debug.Print writes values to the Immediate  Window. To view this window select View->Immediate Window from the menu( the shortcut is Ctrl + G)

 
ImmediateWindow

 
ImmediateSampeText

VBA For Loop Example 2

Now imagine we want to print out the numbers 1 to 20. We would need to add 15 more lines to the example above.

 
However, using a loop we only need to write Debug.Print once.

    For i = 1 To 20
        Debug.Print i
    Next i

 
The output is:

VBA Excel

Output

 
If we needed print the numbers 1 to 1000 then we only need to change the 20 to 1000.

Normally when we write code we would use a variable instead of a number like 20 or 1000. This gives you greater flexibility. It allows you to decide the number of times you wish to run the loop when the code is running. The following example explains this.

VBA For Loop Example 3

A common task in Excel is read all the rows with with data. 

 
The way you approach this task is as follows

  1. Find the last row with data
  2. Store the value in variable
  3. Use the variable to determine how many times the loop runs

 
Using a variable in the loop makes your code very flexible. Your will work no matter how many rows there are.

Let’s have a look at an example. Imagine you receive a sheet with a list of fruit types and their daily sales. You want to count the number of Oranges sold and this list will vary in size depending on sales.

 
The following screenshot shows an example of this list

Sample Data of Fruit Sales

Sample Data of Fruit Sales

 
We can use the code to count the oranges

' https://excelmacromastery.com/
Sub CountFruit()

    ' Get the last row with text
    Dim LastRow As Long
    LastRow = Sheet1.Cells(Sheet1.Rows.Count, 1).End(xlUp).Row

    Dim i As Long, Total As Long
    ' Use LastRow in loop
    For i = 2 To LastRow
        ' Check if cell has text "Orange"
        If Sheet1.Cells(i, 1).Value = "Oranges" Then
            ' Add value in column B to total
            Total = Total + Sheet1.Cells(i, 2).Value
        End If
    Next i

    ' Print total
    Debug.Print "Total oranges sold was:"; Total

End Sub

 
You can try this code for yourself. Change the number of fruit items and you will see that the code still works fine.

If you were to increase the number fruit items to a large value like 10,000 then you will hardly notice the difference in the time it takes to run – almost instantly.

Loops are super fast. This is what makes them so powerful. Imagine performing a manual task on 10,000 cells. It would take a considerable amount of time.

Advantages of the VBA For Loop

4To conclude this section we will list the major advantages of using loops

  • They reduce the lines code you need
  • They are flexible
  • They are fast

 
In the next sections we will look at the different types of loops and how to use them.

The Standard VBA For Loop

The VBA For loop is the most common loop you will use in Excel VBA. The For Loop is used when you can determine the number of times it will be run. For example, if you want to repeat something twenty times.

YouTube Video For Loop

Check out this YouTube Video of the For Loop:

Get the workbook and code for this video here
 

Format of the Standard VBA For Loop

The Standard VBA For Loop has the following format:

For <variable> = <start value> to <end value>
Next <variable>

The start and end values can be variables. Also the variable after Next is optional but it is useful and it makes it clear which for loop it belongs to.

How a For Loop Works

Let’s look at a simple for loop that prints the numbers 1 to 3

    Dim i As Long
    For i = 1 To 3
        Debug.Print i
    Next i

 
How this code works is as follows

i is set to 1
The value of i(now 1) is printed

 
i is set to 2
The value of i(now 2) is printed

 
i is set to 3
The value of i(now 3) is printed

 
If we did not use a loop then the equivalent code would be

    Dim i As Long
    i = i + 1
    Debug.Print i
    i = i + 1
    Debug.Print i
    i = i + 1
    Debug.Print i

 
The i = i + 1 line is used to add 1 to i and is a common way in programming to update a counter.

Using Step with the VBA For Loop

You can see that i is increased by one each time. This is the default. You can specify this interval using Step keyword.

 
The next example shows you how to do this:

    ' Prints the even numbers i.e. 2,4,6,8 ... 20
    For i = 2 To 20 Step 2
        Debug.Print i
    Next i

 
You can use a negative number with Step which will count in reverse

    ' Prints the even numbers in reverse i.e. 20,18,16,14 ... 2
    For i = 20 To 2 Step -2
        Debug.Print i
    Next i

 
Note: if Step is positive then your starting number must be lower than you ending number. The following loop will not run because the starting number 20 is greater than 10. VBA therefore, thinks it has already reached the target value 10.

    ' Will not run as starting number already greater than 10
    For i = 20 To 10 Step 1
        Debug.Print i
    Next i

 
If Step is negative then the start number must be greater than the end number.

Exit the For Loop

Sometimes you may want to leave the loop earlier if a certain condition occurs. For example if you read bad data.

 
You can use Exit For to automatically leave  the loop as shown in the following code

    For i = 1 To 1000

        ' If cell is blank then exit for
        If Cells(i, 1) = "" Then
            MsgBox "Blank Cell found - Data error"
            Exit For
        End If

    Next i

Using the VBA For Loop with a Collection

The For loop can also be used to read items in a Collection.

 
In the following example, we display the name of all the open workbooks

    Dim i As Long
    For i = 1 To Workbooks.Count
        Debug.Print Workbooks(i).FullName
    Next i

Using Nested For Loops

Sometimes you may want to use a loop within a loop. An example of this would be where you want to print the names of the worksheets of each open workbook.

The first loop would go through each workbook. Each time this loop runs it would use a second loop to go through all the worksheets of that workbook. It is actually much easier to do than it sounds.

 
The following code shows how:

' https://excelmacromastery.com/
Sub ListWorksheets()

    Dim i As Long, j As Long
    ' First Loop goes through all workbooks
    For i = 1 To Workbooks.Count

        ' Second loop goes through all the worksheets of workbook(i)
        For j = 1 To Workbooks(i).Worksheets.Count
            Debug.Print Workbooks(i).Name + ":" + Worksheets(j).Name
        Next j

    Next i

End Sub

 
This works as follows:

 
The first loop sets i to 1

 
The second loop then uses the workbook at 1 to go through the worksheets.

 
The first loop sets i to 2

 
The second loop then uses the workbook at 2 to go through the worksheets.

 
and so on

 
It the next section we will use a For Each loop to perform the same task. You will find the For Each version much easier to read.

The VBA For Each Loop

The VBA For Each loop is used to read items from a collection or an array. We can use the For Each loop to access all the open workbooks. This is because Application.Workbooks is a collection of open workbooks.

 
This is a simple example of using the For Each Loop

    Dim wk As Workbook
    For Each wk In Workbooks
        Debug.Print wk.FullName
    Next wk

 Format of the VBA For Each Loop

You can see the format of the VBA for each loop here(See Microsoft For Each Next documentation):
For Each <variable> in <collection>
Next <variable>

To create a For Each loop we need a variable of the same type that the collection holds. In the example here we created a variable of type Workbook.

If the collection has different types of items we can declare the variable as a variant.

VBA contains a collection called Sheets. This is a collection of sheets of type Worksheet(normal) and Chart(when you move a chart to be a full sheet). To go through this collection you would declare the variable as a Variant.

 
The following code uses For Each to print out the name of all the sheets in the current workbook

    Dim sh As Variant
    For Each sh In ThisWorkbook.Sheets
        Debug.Print sh.Name
    Next sh

Order of Items in the For Loop

For Each goes through items in one way only.

For example, if you go through all the worksheets in a workbook it will always go through from left to right. If you go through a range it will start at the lowest cell e.g. Range(“A1:A10”) will return A1,A2,A3 etc.

This means if you want any other order then you need to use the For loop.

 
Both loops in the following example will read the worksheets from left to right:

    ' Both loops read the worksheets from left to right
    Dim wk As Worksheet
    For Each wk In ThisWorkbook.Worksheets
        Debug.Print wk.Name
    Next

    Dim i As Long
    For i = 1 To ThisWorkbook.Worksheets.Count
        Debug.Print ThisWorkbook.Worksheets(i).Name
    Next

 
As you can see the For Each loop is neater to write. However if you want to read the sheets in any other order e.g. right to left then you have to use the for loop:

    ' Reading the worksheets from right to left
    Dim i As Long
    For i = ThisWorkbook.Worksheets.Count To 1 Step -1
        Debug.Print ThisWorkbook.Worksheets(i).Name
    Next

Using the VBA For Each Loop With Arrays

One thing to keep in my is that the For Each loop is that it is read-only when you use it with arrays.

 
The following example demonstrates this:

' https://excelmacromastery.com/
Sub UseForEach()

    ' Create array and add three values
    Dim arr() As Variant
    arr = Array("A", "B", "C")

    Dim s As Variant
    For Each s In arr
        ' Changes what s is referring to - not value of array item
        s = "Z"
    Next

    ' Print items to show the array has remained unchanged
    For Each s In arr
        Debug.Print s
    Next

End Sub

 
In the first loop we try to assign s to “Z”. When happens is that s is now referring the string “Z” and no longer to the item in the array.

In the second loop we print out the array and you can see that none of the values have changed.

 
When we use the For Loop we can change the array item. If we change the previous code to use the For Loop you it will change all the array values to “Z”

' https://excelmacromastery.com/
Sub UsingForWithArray()

    ' Create array and add three values
    Dim arr() As Variant
    arr = Array("A", "B", "C")

    Dim i As Long
    For i = LBound(arr) To UBound(arr)
        ' Changes value at position to Z
        arr(i) = "Z"
    Next

    ' Print items to show the array values have change
    For i = LBound(arr) To UBound(arr)
        Debug.Print arr(i)
    Next

End Sub

If your Collection is storing Objects the you can change the items using a For Each loop.

Using Nested For Each Loops

We saw already that you can have a loop inside other loops. Here is the example from above:

' https://excelmacromastery.com/
Sub ListWorksheets()

    Dim i As Long, j As Long
    ' First Loop goes through all workbooks
    For i = 1 To Workbooks.Count

        ' Second loop goes through all the worksheets of workbook(i)
        For j = 1 To Workbooks(i).Worksheets.Count
            Debug.Print Workbooks(i).Name + ":" + Worksheets(j).Name
        Next j

    Next i

End Sub

This time we will use the For Each loop to perform the same task:

' https://excelmacromastery.com/
Sub ReadAllWorksheets()

    Dim wk As Workbook, sh As Worksheet
    ' Read each workbook
    For Each wk In Workbooks

        ' Read each worksheet in the wk workbook
        For Each sh In wk.Worksheets
            ' Print workbook name and worksheet name
            Debug.Print wk.Name + ": " + sh.Name
        Next sh

    Next wk

End Sub

As you can see this is a neater way of performing this task than using the For Loop:

This code run as follows:

  1. Get the first Workbook from the Workbooks collection
  2. Go through all the worksheets in this workbook
  3. Print the workbook/worksheet details
  4. Get the next workbooks in the collection
  5. Repeat steps 2 to 3
  6. Continue until no more workbooks are left in the collection

How to Loop Through a Range

In Excel VBA, the most common use of a For Loop is to read through a range.

Imagine we have the data set in the screenshot below. Our task is to write code that will read through the data and copy the amounts to the column J. We are only going to copy amounts that are greater than 200,000.

VBA For Loop Range

 
The following example shows how we do it:

' Read through an Excel Range using the VBA For Loop
' https://excelmacromastery.com/
Sub ForLoopThroughRange()

    ' Get the worksheet
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Worksheets("Sheet1")
    
    ' Get the Range
    Dim rg As Range
    Set rg = sh.Range("A1").CurrentRegion
    
    ' Delete existing output
    sh.Range("J1").CurrentRegion.ClearContents
    
    ' Set the first output row
    Dim row As Long
    row = 1
    
    ' Read through all the rows using the For Loop
    Dim i As Long
    For i = 2 To rg.Rows.Count
    
        ' Check if amount is greater than 200000
        If rg.Cells(i, 4).Value > 200000 Then
        
            ' Copy amount to column m
            sh.Cells(row, "J").Value = rg.Cells(i, 4).Value
            
            ' Move to next output row
            row = row + 1
            
        End If
        
    Next i
    
End Sub

 
This is a very basic example of copying data using Excel VBA. If you want a complete guide to copying data using Excel VBA then check out this post

Summary of the VBA For Loops

The Standard VBA For Loop

  • The For  loop is slower than the For  Each loop.
  • The For loop can go through a selection of items e.g. 5 to 10.
  • The For loop can read items in reverse e.g. 10 to 1.
  • The For loop is not as neat to write as the For Each Loop especially with nested loops.
  • To exit a For loop use Exit For.

The VBA For Each Loop

  • The For Each loop is faster than the For loop.
  • The For Each loop goes through all items in the collectionarray.
  • The For Each loop can go through items in one order only.
  • The For Each loop is neater to write than a For Loop especially for nested loops.
  • To exit a For Each loop use Exit For.

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

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

К циклам VBA относятся:

  • Цикл For
  • Цикл Do While
  • Цикл Do Until

Далее мы подробно рассмотрим каждый из этих циклов.

Содержание

  1. Оператор цикла «For» в Visual Basic
  2. Цикл «For … Next»
  3. Цикл «For Each»
  4. Оператор прерывания цикла «Exit For»
  5. Цикл «Do While» в Visual Basic
  6. Цикл «Do Until» в Visual Basic

Оператор цикла «For» в Visual Basic

Структура оператора цикла For в Visual Basic может быть организована в одной из двух форм: как цикл For … Next или как цикл For Each.

Цикл «For … Next»

Цикл For … Next использует переменную, которая последовательно принимает значения из заданного диапазона. С каждой сменой значения переменной выполняются действия, заключённые в теле цикла. Это легко понять из простого примера:

For i = 1 To 10
   Total = Total + iArray(i)
Next i

В этом простом цикле For … Next используется переменная i, которая последовательно принимает значения 1, 2, 3, … 10, и для каждого из этих значений выполняется код VBA, находящийся внутри цикла. Таким образом, данный цикл суммирует элементы массива iArray в переменной Total.

В приведённом выше примере шаг приращения цикла не указан, поэтому для пошагового увеличения переменной i от 1 до 10 по умолчанию используется приращение 1. Однако, в некоторых случаях требуется использовать другие значения приращения для цикла. Это можно сделать при помощи ключевого слова Step, как показано в следующем простом примере.

For d = 0 To 10 Step 0.1
   dTotal = dTotal + d
Next d

Так как в приведённом выше примере задан шаг приращения равный 0.1, то переменная dTotal для каждого повторения цикла принимает значения 0.0, 0.1, 0.2, 0.3, … 9.9, 10.0.

Для определения шага цикла в VBA можно использовать отрицательную величину, например, вот так:

For i = 10 To 1 Step -1
   iArray(i) = i
Next i

Здесь шаг приращения равен -1, поэтому переменная i с каждым повторением цикла принимает значения 10, 9, 8, … 1.

Цикл «For Each»

Цикл For Each похож на цикл For … Next, но вместо того, чтобы перебирать последовательность значений для переменной-счётчика, цикл For Each выполняет набор действий для каждого объекта из указанной группы объектов. В следующем примере при помощи цикла For Each выполняется перечисление всех листов в текущей рабочей книге Excel:

Dim wSheet As Worksheet

For Each wSheet in Worksheets
   MsgBox "Найден лист: " & wSheet.Name
Next wSheet

Оператор прерывания цикла «Exit For»

Оператор Exit For применяется для прерывания цикла. Как только в коде встречается этот оператор, программа завершает выполнение цикла и переходит к выполнению операторов, находящихся в коде сразу после данного цикла. Это можно использовать, например, для поиска определённого значения в массиве. Для этого при помощи цикла просматривается каждый элемент массива. Как только искомый элемент найден, просматривать остальные нет необходимости – цикл прерывается.

Применение оператора Exit For продемонстрировано в следующем примере. Здесь цикл перебирает 100 записей массива и сравнивает каждую со значением переменной dVal. Если совпадение найдено, то цикл прерывается:

For i = 1 To 100
   If dValues(i) = dVal Then
      IndexVal = i
      Exit For
   End If
Next i

Цикл «Do While» в Visual Basic

Цикл Do While выполняет блок кода до тех пор, пока выполняется заданное условие. Далее приведён пример процедуры Sub, в которой при помощи цикла Do While выводятся последовательно числа Фибоначчи не превышающие 1000:

'Процедура Sub выводит числа Фибоначчи, не превышающие 1000
Sub Fibonacci()
   Dim i As Integer 'счётчик для обозначения позиции элемента в последовательности
   Dim iFib As Integer 'хранит текущее значение последовательности
   Dim iFib_Next As Integer 'хранит следующее значение последовательности
   Dim iStep As Integer 'хранит размер следующего приращения

   'инициализируем переменные i и iFib_Next
   i = 1
   iFib_Next = 0
   'цикл Do While будет выполняться до тех пор, пока значение
   'текущего числа Фибоначчи не превысит 1000

   Do While iFib_Next < 1000
      If i = 1 Then
         'особый случай для первого элемента последовательности
         iStep = 1
         iFib = 0
      Else
         'сохраняем размер следующего приращения перед тем, как перезаписать
         'текущее значение последовательности
         iStep = iFib
         iFib = iFib_Next
      End If

      'выводим текущее число Фибоначчи в столбце A активного рабочего листа
      'в строке с индексом i
      Cells(i, 1).Value = iFib
      'вычисляем следующее число Фибоначчи и увеличиваем индекс позиции элемента на 1
      iFib_Next = iFib + iStep
      i = i + 1
   Loop

End Sub

В приведённом примере условие iFib_Next < 1000 проверяется в начале цикла. Поэтому если бы первое значение iFib_Next было бы больше 1000, то цикл бы не выполнялся ни разу.

Другой способ реализовать цикл Do While – поместить условие не в начале, а в конце цикла. В этом случае цикл будет выполнен хотя бы раз, не зависимо от того, выполняется ли условие.

Схематично такой цикл Do While с проверяемым условием в конце будет выглядеть вот так:

Do
...
Loop While iFib_Next < 1000

Цикл «Do Until» в Visual Basic

Цикл Do Until очень похож на цикл Do While: блок кода в теле цикла выполняется раз за разом до тех пор, пока заданное условие выполняется (результат условного выражения равен True). В следующей процедуре Sub при помощи цикла Do Until извлекаются значения из всех ячеек столбца A рабочего листа до тех пор, пока в столбце не встретится пустая ячейка:

iRow = 1
Do Until IsEmpty(Cells(iRow, 1))
   'Значение текущей ячейки сохраняется в массиве dCellValues
   dCellValues(iRow) = Cells(iRow, 1).Value
   iRow = iRow + 1
Loop

В приведённом выше примере условие IsEmpty(Cells(iRow, 1)) находится в начале конструкции Do Until, следовательно цикл будет выполнен хотя бы один раз, если первая взятая ячейка не пуста.

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

Do
...
Loop Until IsEmpty(Cells(iRow, 1))

Оцените качество статьи. Нам важно ваше мнение:

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