Vba excel цикл while wend

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

Цикл While… Wend в VBA Excel предназначен для повторения блока операторов до тех пор, пока выполняется заданное условие (возвращается значение True). По своему функционалу его можно считать ограниченной версией цикла Do While… Loop, который позволяет проверять условие как до, так и после выполнения операторов, и принудительно завершать цикл с помощью оператора Exit Do. У цикла While… Wend таких возможностей нет: условие может быть задано только перед блоком операторов, а принудительный выход из цикла не предусмотрен.

While condition

    [ statements ]

Wend

Компоненты цикла While… Wend

Компонент Описание
condition Обязательный атрибут. Условие выполнения цикла. Выражение, возвращающее значение типа Boolean.
statements Необязательный* атрибут. Операторы вашего кода.

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

Примеры циклов While… Wend

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

Sub test1()

Dim a As Byte

  While a < 100

    a = a + 7

  Wend

MsgBox a

End Sub

Информационное сообщение MsgBox выведет число 105.

Проход по строкам листа

Допустим, на листе Excel есть таблица, расположенная в левом верхнем углу, начиная с ячейки A1, и под ней — пустая строка. Таблица содержит следующие данные:

Товар Кол-во Цена Сумма
Батон 1 33
Лимон 2 30
Молоко 3 55
Хлеб 1 30
Чипсы 5 18

Исходя из этих данных, необходимо, используя цикл While… Wend для прохода по строкам листа Excel, рассчитать сумму по каждому наименованию товара и записать ее в четвертую графу, а также в первую пустую строку записать слово «Итого:» (в третью графу) и итоговую сумму (в четвертую графу).

Sub test2()

Dim i As Long, a As Double

i = 2

  While Cells(i, 1) <> «»

    Cells(i, 4) = Cells(i, 2) * Cells(i, 3)

    a = a + Cells(i, 4)

    i = i + 1

  Wend

Cells(i, 3) = «Итого:»

Cells(i, 4) = a

End Sub

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


Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    In this article, we are going to see about While Wend loop in Excel VBA using a suitable example.

    Implementation :

    In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available. 

    The Developer Tab can be enabled easily by a two-step process :

    • Right-click on any of the existing tabs in the top of the Excel window.
    • Now select Customize the Ribbon from the pop-down menu.

    • In the Excel Options Box, check the box Developer to enable it and click on OK.

    • Now, the Developer Tab is visible.

    Now click on the Visual Basic option in the Developer tab and make a new module to write the program using the Select Case statement.

    Developer  -> Visual Basic -> Tools -> Macros
    • Now create a Macro and give any suitable name.

    • This will open the Editor window where can write the code.

    While Wend Loop

    In a while loop all the statements will execute inside the loop until the provided condition becomes FALSE. The loop terminates only when the condition becomes FALSE. In Excel the keyword While is used to start the while loop and Wend is used to end the while loop.

    1. The statements inside the while loop execute when the condition is TRUE.

    2. When the condition is FALSE, the loop terminates and the control moves to the line after the keyword Wend.

    The syntax is :

    While boolean_condition(s)/expression(s)
        Statement 1
        Statement 2
        Statement 3
        ...
        Statement n
    Wend

    Flow Diagram

    Example : Print the age of all the employees in an organization whose age falls between thirty to forty years.

    Code :

    Sub While_Age_Emp()
    'Initialize and declare the age of the employee
    Dim Age As Integer: Age = 30
    'Condition to print the age of employees between 30 to 40 years
    While Age < 39
        Age = Age + 1
        MsgBox ("Age:" & Age)
    Wend
    End Sub

    The condition for the above code is Age < 39. When the age of the employee becomes 40 the condition becomes FALSE and the loop terminates. So, it will print the ages from 31 to 39 respectively in the message box of Excel.

    Output :

    Age : 31

    Age : 32

    Age : 33

    Age : 34

    Age : 35

    Age : 36

    Age : 37

    Age : 38

    Age : 39

    Like Article

    Save Article

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

    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.

    В этом учебном материале вы узнаете, как использовать Excel оператор WHILE … WEND для создания цикла WHILE в VBA с синтаксисом и примерами.

    Описание

    Оператор Microsoft Excel WHILE … WEND используется для создания цикла WHILE в VBA. Вы используете цикл WHILE, когда не знаете, сколько раз вы хотите выполнить код VBA в теле цикла. В цикле WHILE тело цикла может не выполняться ни разу. Оператор WHILE … WEND — это встроенная в Excel функция, которая относится к категории логических функций. Её можно использовать как функцию VBA в Excel.
    В качестве функции VBA вы можете использовать эту функцию в коде макроса, который вводится через редактор Microsoft Visual Basic Editor.

    Синтаксис

    Синтаксис для создания цикла WHILE с использованием оператора WHILE … WEND в Microsoft Excel:

    While condition {…statements…}
    Wend

    Аргументы или параметры

    condition
    Условие проверяется при каждом проходе цикла.
    Если condition оценивается как ИСТИНА, тело цикла выполняется.
    Если condition оценивается как ЛОЖЬ, цикл завершается.
    statement
    Операторы кода выполняемые при каждом проходе через цикл.

    Возвращаемое значение

    Оператор WHILE … WEND создает цикл WHILE в VBA.

    Примечание

    • См. также оператор FOR … NEXT, чтобы создать цикл FOR в VBA.

    Применение

    • Excel для Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 для Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

    Тип функции

    • Функция VBA

    Пример (как функция VBA)

    Оператор WHILE … WEND может использоваться только в коде VBA в Microsoft Excel.
    Давайте посмотрим, как создать цикл WHILE в Microsoft Excel.

    Цикл WHILE

    Например:

    Sub While_Loop_Example

      Dim LTotal As Integer

      LTotal = 1

      While LTotal<5

       MsgBox (LTotal)

       LTotal = LTotal + 1

      Wend

    End Sub

    В этом примере цикл WHILE управляется условием While LTotal<5. Это условие проверяется при каждом проходе цикла.
    Если условие — ИСТИНА, то код VBA отобразит окно сообщения со значением переменной LTotal.
    Если условие — ЛОЖЬ, цикл прекращается. Этот код отобразит 4 окна сообщений со следующими значениями: 1, 2, 3 и 4. Когда LTotal достигнет 5, цикл завершится.

    Двойной цикл WHILE

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

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    Sub Double_While_Loop_Example

      Dim LCounter1 As Integer

      Dim LCounter2 As Integer

      LCounter1 = 1

      LCounter2 = 8

      While LCounter1<5

       While LCounter2<10

         MsgBox (LCounter1 & «-« & LCounter2)

         LCounter2 = LCounter2 + 1

       Wend

       LCounter2 = 8

       LCounter1 = LCounter1 + 1

      Wend

    End Sub

    Здесь у нас есть 2 цикла WHILE. Внешний цикл WHILE управляется переменной LCounter1. Внутренний цикл WHILE управляется переменной LCounter2. В этом примере внешний цикл WHILE будет повторяться 4 раза (начиная с 1 и заканчивая 4), а внутренний цикл WHILE будет повторяться 2 раза (начиная с 8 и заканчивая 9). Во внутреннем цикле код будет каждый раз отображать окно сообщения со значением LCounter1-LCounter2. Таким образом, в этом примере будет отображаться 8 окон сообщений со следующими значениями: 1-8, 1-9, 2-8, 2-9, 3-8, 3-9, 4-8 и 4-9. Заметим, что при выходе из внутреннего цикла WHILE мы сбрасываем счетчик внутреннего цикла WHILE обратно на 8 с помощью оператора LCounter2 = 8. Это необходимо для того, чтобы внутренний цикл WHILE выполнялся снова, так как LCounter2 будет равен 10 после выхода внутренний цикл WHILE в первый раз.
    Если мы оставим LCounter2 равным 10, условие для кода внутреннего цикла WHILE будет оцениваться как ЛОЖЬ и каждый раз завершать цикл.

    “Now… We are going in a loop” ― Ramakrishna, Springs of Indian Wisdom

     
    This post provides a complete guide to the VBA Do While and VBA While Loops. (If you’re looking for information about the VBA For and For Each loops go here)

    The VBA While loop exists to make it compatible with older code. However, Microsoft recommends that you use the Do Loop as it is more “structured and flexible”. Both of these loops are covered in this post.

    For a quick guide to these loops check out the Quick Guide Table below.

    If you are looking for something in particular, you can check out the Table of Contents below(if it’s not visible click on the post header).

    A Quick Guide to VBA While Loops

    Loop format Description Example
    Do While … Loop Runs 0 or more time while condition is true Do While result = «Correct»
    Loop
    Do … Loop While Runs 1 or more times while condition is true Do
    Loop While result = «Correct»
    Do Until … Loop Runs 0 or more times until condition is true Do Until result <> «Correct»
    Loop
    Do … Until Loop Runs 1 or more times until condition is true Do
    Loop Until result <> «Correct»
    While … Wend Runs 0 or more times while condition is true.

    Note: this loop is considered obsolete.

    While result = «Correct»
    Wend
    Exit the Do Loop Exit Do Do While i < 10
       i = GetTotal
       If i < 0 Then
          Exit Do
       End If
    Loop

    Introduction

    If you have never use loops before then you may want to read What are Loops and Why Do You Need Them from my post on the For Loop.

    I am going to be mainly concentrating on the Do Loop in this post. As I mentioned above, we have seen the While Wend loop is considered obsolete. For completeness, I have included a section on While Wend later in the post.

    So first of all why do we need Do While loops when we already have For loops?

    For Loops Versus Do While Loops

    When we use a For Loop, we know in advance how many times we want to run it. For example, we may want to run the loop once for each item in a Collection, Array or Dictionary.

     
    In the following code example, we know at the start of each loop, how many times it will run.

     
    ' runs 5 times
    For i = 1 To 5
    
    ' runs once for each item in the collection
    For i = 1 To coll.Count
    
    ' runs once for each item in the arr
    For i = LBound(arr) To coll.lbound(arr)
    
    ' runs once for each value between 1 and the value in lastRow
    For i = 1 To lastRow
    
    ' runs once for each item in the collection
    For Each s In coll
    

     
    The Do Loop is different. The Do Loop runs

    1. While a conditon is true
    2.  
      Or
       

    3. Until a condition is true

     
    In other words, the number of times the loops runs is not relevant in most cases.

    So what is a condition and how do we use them?

    Conditions

    A condition is a statement that evaluates to true or false. They are mostly used with Loops and If statements. When you create a condition you use signs like >,<,<>,>=,=.

     
    The following are examples of conditions

    Condition This is true when
    x < 5 x is less than 5
    x <= 5 x is less than or equal to 5
    x > 5 x is greater than 5
    x >= 5 x is greater than or equal to 5
    x = 5 x is equal to 5
    x <> 5 x does not equal 5
    x > 5 And x < 10 x is greater than 5 AND x is less than 10
    x = 2 Or x >10 x is equal to 2 OR x is greater than 10
    Range(«A1») = «John» Cell A1 contains text «John»
    Range(«A1») <> «John» Cell A1 does not contain text «John»

     
    You may have noticed x=5 as a condition. This should not be confused with x=5 when used as an assignment.

     
    For example

    ' means: the value 6 will be stored in x
    x = 6
    
    ' means: is x equal to 6?
    If x = 6
    
    ' means: is x equal to 6?
    Do While x = 6
    

     
    The following table demonstrates how equals is used in conditions and assignments

    Using Equals Statement Type Meaning
    Loop Until x = 5 Condition Is x equal to 5
    Do While x = 5 Condition Is x equal to 5
    If x = 5 Then Condition Is x equal to 5
    For x = 1 To 5 Assignment Set the value of x to 1, then to 2 etc.
    x = 5 Assignment Set the value of x to 5
    b = 6 = 5 Assignment and Condition Assign b to the result of condition 6 = 5
    x = MyFunc(5,6) Assignment Assign x to the value returned from the function

    The Do Loop Format

    The Do loop can be used in four ways and this often causes confusion. However, there is only a slight difference in each of these four ways.

     
    Do is always at the start of the first line and Loop is always at the end of the last line

    Do 
    Loop
    

     
    We can add a condition after either line

    Do [condition]
    Loop
    
    Do 
    Loop [condition]
    

     
    The condition is preceded by While or Until which gives us these four possibilities

    Do While [condition]
    Loop
    
    Do Until [condition]
    Loop
    
    Do 
    Loop While [condition]
    
    Do 
    Loop Until [condition]
    
     

     
    Let’s have a look at some examples to make this clearer.

    A Do Loop Example

    Imagine you want the user to enter a list of items. Each time the user enters an item you print it to the Immediate Window. When the user enters a blank string, you want the application to end.

    In this case the For loop would not be suitable as you do not know how many items the user will enter. The user could enter the blank string first or on the hundredth attempt. For this type of scenario, you would use a Do loop.

     
    The following code shows an example of this

        Dim sCommand As String
    
        Do
            ' Get user input
            sCommand = InputBox("Please enter item")
    
            ' Print to Immediate Window(Ctrl G to view)
            Debug.Print sCommand
    
        Loop While sCommand <> ""
    

     
    The code enters the loop and continues until it reaches the “Loop While” line. At this point, it checks whether the condition evaluates to true or false.

    • If the condition evaluates to false then the code exits the loop and continues on.
    • If the condition evaluates to true then the code returns to the Do line and runs through the loop again.

     
    The difference between having the condition on the Do line and on the Loop line is very simple

    When the condition is on the Do line, the loop may not run at all. So it will run zero or more times.
    When the condition is on the Loop line, the loop will always run at least once. So it will run one or more times.

     
    In our the last example, the condition is on the Loop line because we always want to get at least one value from the user. In the following example, we use both versions of the loop. The loop will run while the user does not the enter the letter ‘n’

    ' https://excelmacromastery.com/
    Sub GetInput()
    
        Dim sCommand As String
    
        ' Condition at start
        Do While sCommand <> "n"
            sCommand = InputBox("Please enter item for Loop 1")
        Loop
    
        ' Condition at end
        Do
            sCommand = InputBox("Please enter item for Loop 2")
        Loop While sCommand <> "n"
    
    End Sub
    

     
    In the above example, both loops will behave the same.

    However, if we set sCommand to ‘n’ before the Do While loop starts, then the code will not enter the loop.

    ' https://excelmacromastery.com/
    Sub GetInput2()
    
        Dim sCommand As String
        sCommand = "n"
    
        ' Loop will not run as command is "n"
        Do Whilel sCommand <> "n"
            sCommand = InputBox("Please enter item for Loop 1")
        Loop
    
        ' Loop will still run at least once
        Do
            sCommand = InputBox("Please enter item for Loop 2")
        Loop While sCommand <> "n"
    
    End Sub
    

     
    The second loop in the above example(i.e. Loop While) will always run at least once.

    While Versus Until

    When you use the Do Loop the condition mush be preceded by Until or While.

    Until and While are essentially the opposite of each other. They are used in VBA in a similar way to how they are used in the English language. 

     
    For example

    • Leave the clothes on the line Until it rains
    • Leave the clothes on the line While it does not rain

     
    another example

    • Stay in bed Until it is light
    • Stay in bed While it is dark

     
    yet another example

    • repeat Until the count is greater than or equals ten
    • repeat While the count is less than ten

     
    As you can see – using Until and While is just the opposite way of writing the same condition.

    Examples of While and Until

    The following code shows the ‘While’ and ‘Until’ loops side by side. As you can see the only difference is the condition is reversed. Note: The signs <> means ‘does not equal’.

    ' https://excelmacromastery.com/
    Sub GetInput()
    
        Dim sCommand As String
    
        ' Condition at start
        Do Until sCommand = "n"
            sCommand = InputBox("Please enter item for Loop 1")
        Loop
    
        Do While sCommand <> "n"
            sCommand = InputBox("Please enter item for Loop 1")
        Loop
    
        ' Condition at end
        Do
            sCommand = InputBox("Please enter item for Loop 2")
        Loop Until sCommand = "n"
    
        Do
            sCommand = InputBox("Please enter item for Loop 2")
        Loop While sCommand <> "n"
    
    End Sub
    

     
    First loop: will only start if sCommand does not equal ‘n’.
    Second loop: will only start if sCommand does not equal ‘n’.
    Third loop: will run at least once before checking sCommand.
    Fourth loop: will run at least once before checking sCommand.

    Example: Checking Objects

    An example of where Until and While are useful is for checking objects. When an object has not been assigned it has the value Nothing.

     
    So when we declare a workbook variable in the following example it has a value of nothing until we assign it to a valid Workbook

        Dim wrk As Workbook
    

     
    The opposite of Nothing is Not Nothing which can be confusing.

    Imagine we have two functions called GetFirstWorkbook and GetNextWorkbook which return some workbook objects. The code will print the name of the workbook until the functions no longer return a valid workbook.

     
    You can see the sample code here

        Dim wrk As Workbook
        Set wrk = GetFirstWorkbook()
    
        Do Until wrk Is Nothing
            Debug.Print wrk.Name
            Set wrk = GetNextWorkbook()
        Loop
    

     
    To write this code using Do While would be more confusing as the condition is Not Is Nothing

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

     
    This makes the code clearer and having clear conditions is always a good thing. To be honest this is a very small difference and choosing between While and Until really comes down to a personal choice.

    Exit Do Loop

    We can exit any Do loop by using the Exit Do statement.

    The following code shows an example of using Exit Do

    Do While i < 1000
         If Cells(i,1) = "Found" Then 
             Exit Do
         End If
         i = i + 1
    Loop 
    

     
    In this case we exit the Do Loop if a cell contains the text “Found”.

    While Wend

    This loop is in VBA to make it compatible with older code. Microsoft recommends that you use the Do loops as they are more structured.

    From MSDN: “The Do…Loop statement provides a more structured and flexible way to perform looping.”

    Format of the VBA While Wend Loop

    The VBA While loop has the following format

    While <Condition>
    Wend

    While Wend vs Do

    The different between the VBA While and the VBA Do Loop is :

    1. While can only have a condition at the start of the loop.
    2. While does not have a Until version.
    3. There is no statement to exit a While loop like Exit For or Exit Do.

     
    The condition for the VBA While loop is the same as for the VBA Do While loop. The two loops in the code below perform exactly the same way

    ' https://excelmacromastery.com/
    Sub GetInput()
    
        Dim sCommand As String
    
        Do While sCommand <> "n"
            sCommand = InputBox("Please enter item for Loop 1")
        Loop
    
        While sCommand <> "n"
            sCommand = InputBox("Please enter item for Loop 2")
        Wend
    
    End Sub
    
    

     Infinite Loop

    Even if you have never written code in your life I’m sure you’ve heard the phrase Infinite Loop. This is a loop where the condition will never be met. It normally happens when you forget to update the count.

     
    The following code shows an infinite loop

        Dim cnt As Long
        cnt = 1
    
        ' Do not run - this is an infinite loop
        Do While cnt <> 5
    
        Loop
    
    

     
    In this example cnt is set to 1 but it is never updated. Therefore the condition will never be met – cnt will always be less than 5.

     
    In the following code the cnt is being updated each time so the condition will be met.

        Dim cnt As Long
        cnt = 1
    
        Do While cnt <> 5
            cnt = cnt + 1
        Loop
    
    

     
    As you can see using a For Loop is safer for counting as it automatically updates the count in a loop. The following is the same loop using For.

        Dim i As Long
        For i = 1 To 4
    
        Next i
    
    

     
    This is clearly a better way of doing it. The For Loop sets the initial value, condition and count in one line.

     
    Of course it is possible to have an infinite loop using For – It just takes a bit more effort 🙂

        Dim i As Long
        ' DO NOT RUN - Infinite Loop
        For i = 1 To 4
            ' i will never reach 4
            i = 1
        Next i
    
    

    Dealing With an Infinite Loop

    When you have an infinite loop – VBA will not give an error. You code will keep running and the Visual Basic editor will not respond.

    In the old days you could break out of a loop by simply pressing Ctrl and Break. Nowadays different Laptops use different key combinations. It is a good idea to know what this is for your laptop so that if an infinite loop occurs you can stop the code easily.

    You can also break out of a loop by killing the process. Press Ctrl+Shift+Esc. Under the Processes tab look for Excel/Microsoft Excel. Right-click on this and select “End Process”. This will close Excel and you may lose some work – so it’s much better to use Ctrl+Break or it’s equivalent.

    Using Worksheet Functions Instead of Loops

    Sometimes you can use a worksheet function instead of using a loop.

    For example, imagine you wanted to add the values in a list of cells. You could do this using a loop but it would be more efficient to use the worksheet function Sum. This is quicker and saves you a lot of code.

     
    It is very easy to use the Worksheet functions. The following is an example of using Sum and Count

    ' https://excelmacromastery.com/
    Sub WorksheetFunctions()
    
        Debug.Print WorksheetFunction.Sum(Range("A1:A10"))
    
        Debug.Print WorksheetFunction.Count(Range("A1:A10"))
    
    End Sub
    
    

     
    The following example use a loop to perform the same action. As you can see it is a much longer way of achieving the same goal

    ' https://excelmacromastery.com/
    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
    
    

    Summary

    The Do While Loop

    • The Do loop can be used in 4 ways.
    • It can be used with While at the start or end, Do While .. Loop, Do … Loop While
    • It can be used with Until at the start or end, Do Until .. Loop, Do … Loop Until
    • While and Until use the opposite condition to each other.
    • An Infinite loop occurs if your exit condition will never be met.
    • Sometimes using a worksheet function is more efficient than using a loop.

    The While Wend Loop

    • The While Wend loop is obsolete and you can use the Do Loop instead.

    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 and all the tutorials.

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

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