Цикл с постусловием vba excel

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

Цикл Do While… Loop в VBA Excel предназначен для повторения блока операторов пока выполняется заданное условие (возвращается значение True). Синтаксис этого цикла аналогичен синтаксису цикла Do Until… Loop, который повторяется до тех пор, пока условие не выполняется (возвращается значение False).

Синтаксис цикла Do While… Loop существует в двух вариантах, определяющих, когда проверяется условие.


Условие проверяется до выполнения операторов:

Do While condition

    [ statements ]

    [ Exit Do ]

    [ statements ]

Loop


Условие проверяется после выполнения операторов:

Do

    [ statements ]

    [ Exit Do ]

    [ statements ]

Loop While condition


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

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

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

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

**Очень полезный оператор для цикла Do While… Loop, так как при некоторых обстоятельствах он может стать бесконечным. Если такой риск существует, следует предусмотреть возможность выхода из бесконечного цикла VBA с помощью оператора Exit Do.

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

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

Цикл Do While… Loop с условием до исполняемых операторов:

Sub test1()

Dim a As Byte

  Do While a < 10

    a = a + 1

  Loop

MsgBox a

End Sub

Цикл Do While… Loop с условием после исполняемых операторов:

Sub test2()

Dim a As Byte

  Do

    a = a + 1

  Loop While a < 10

MsgBox a

End Sub

В обоих случаях окно MsgBox выведет число 10. Когда значение переменной a будет равно 10, проверяемое условие выдаст значение False, и цикл будет остановлен.

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

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

Дни Игрок Брошено Попало в цель
1 день Белка 1 15 6
1 день Белка 2 12 7
2 день Белка 1 14 8
2 день Белка 2 16 7
3 день Белка 1 20 9
3 день Белка 2 14 6
4 день Белка 1 26 10
4 день Белка 2 13 5
5 день Белка 1 17 4
5 день Белка 2 21 7

Исходя из этих данных необходимо узнать, сколько шишек осталось у Белки 1 в дупле. Для этого необходимо вычесть из 100 шишек количество выброшенных Белкой 1 и прибавить шишки, заброшенные в ее дупло Белкой 2. Вычисления начинаем со второй строки (в первой заголовки) и в условии для цикла Do While… Loop указываем «первая ячейка текущей строки не является пустой». Таблица должна начинаться с первой ячейки рабочего листа «A1», и под ней, как минимум, одна строка должна быть пустой, точнее, первая ячейка этой строки.

Sub test3()

Dim i As Long, n As Long

i = 2

n = 100

  Do While Cells(i, 1) <> «»

    If Cells(i, 2) = «Белка 1» Then

      n = n Cells(i, 3)

    Else

      n = n + Cells(i, 4)

    End If

    i = i + 1

  Loop

MsgBox n

End Sub

Результат, выведенный в информационном сообщении MsgBox, будет равен 40. Вы можете скопировать таблицу на рабочий лист книги Excel и поэкспериментировать с кодом VBA.

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

Пример бесконечного цикла:

Sub test4()

Dim a As Byte

  Do While a < 10

  a = a + 1

    If a = 9 Then

      a = 0

    End If

  Loop

End Sub

При запуске этой процедуры цикл Do While… Loop начинает выполняться бесконечно. Мне приходилось останавливать бесконечные циклы VBA в Excel 2000 и Excel 2016. В Excel 2000 помогло сочетание клавиш Ctrl+Break, а в Excel 2016 при закрытии редактора VBA крестиком появляется окно:

Информационное окно «Microsoft Excel не отвечает»

Информационное окно «Microsoft Excel не отвечает»

Ожидать отклика программы нет смысла, поэтому нажимаем «Перезапустить программу» или «Закрыть программу».

Совет: перед запуском процедуры с циклом Do While… Loop, который может стать бесконечным, обязательно сохраните книгу, иначе, при принудительном закрытии редактора VBA ваши изменения будут утеряны. Кроме того, при принудительном закрытии редактора VBA, Excel может отключить макросы. Включите их в окне «Центр управления безопасностью», открыть которое можно по ссылке «Безопасность макросов» на ленте в разделе «Разработчик». Подробнее о включении макросов в разных версиях Excel читайте в статье: Как разрешить выполнение макросов в Excel?.

Пример использования оператора Exit Do:

Sub test5()

Dim a As Byte, n As Long

  Do While a < 10

  a = a + 1

  n = n + 1

    If a = 9 Then

      a = 0

    End If

    If n = 1000 Then

      Exit Do

    End If

  Loop

MsgBox n

End Sub

Когда число итераций цикла дойдет до 1000, он будет завершен, и информационное сообщение MsgBox выведет на экран число повторений цикла Do While… Loop из этого примера.


“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 Do while is a loop in which you need to specify a condition and that condition must remain true for the loop to run. In simple words, first, it checks that the condition you have specified is true or not and if that condition is true it runs the loop, otherwise nothing.

In each iteration, it tests for the condition and only then executes the statement. Imagine, you want to add worksheets in Excel while the full account of the worksheets is 12 or below. In this case, you can use the do-while loop to write that code.

Syntax

Following is the syntax for the VBA For Each Next Loop.

Do While Condition
    [statements]
Loop
  1. Condition: It is the condition that you specify, and this condition must be true to run the loop.
  2. Statement: The line(s) of code are you want Do While Loop to execute condition is true.
  3. Loop: It’s the end statement for one iteration of the loop and tells VBA to move back to test the condition again.

Example to Understand the DO While Loop

To understand Do While Loop, let’s write a code to add worksheets in a workbook hey while the total count of the worksheets is below twelve. You do not need to tell VBA how many sheets to add and you will always have a total of 12 sheets every time when you run this code.

Use the following steps:

  1. First, you need to type the keyboard “Do While”.
    2-type-the-keyword-do-while
  2. Next you need to write a condition that can check if the total number of worksheets in the workbook are lower than twelve.
  3. For this, you need to use the below code, that count the total count of the worksheets then compare it with the number twelve.
    3-condition-to-check-worksheets
  4. Next you need to write the code to add a worksheet. This code will run when the condition that you have specified is true.
    4-code-to-add-worksheet
  5. And, in the end, type the keyword “Loop” to end the code.
    5-type-loop-to-end-the-code

Here is the full code that you have just written:

Sub vba_do_while_loop()

    Do While ActiveWorkbook.Worksheets.Count < 12   
        Sheets.Add   
    Loop

End Sub

Now let me tell you how this code works: The condition you have specified checks for the total number of worksheets in the workbook and then you have a lower than operator that checks for the count of the worksheets against twelve.

When the count of the worksheet is below twelve the loop will continue to run and keep on adding new worksheets but once the count of the worksheets will reach twelve it will stop the loop.

It’s in simple words the loop will continue to run while the count of the worksheets is below twelve.

Here’s the thing, with the code that you have just written, you don’t need to specify the count of the worksheets that you want to add, but if you go with the next loop you need to specify the count of the worksheets that you want to add.

Do Loop While is an extended version of Do While Loop as it works in the same way but there is a slight difference while testing the condition.

In Do Loop While, it runs one iteration of the loop before testing the condition that you have specified and if the condition is true it will continue to loop.

Let’s say, you want to write a code to verify a password to run a code and continue to loop while the password is incorrect (we see it in the example).

Syntax

Following is the syntax for the VBA Do Loop While.

  1. Do: It is the starting keyword for the Do Loop While.
  2. Statement: It is the line(s) of the code that you want to run in the loop.
  3. Loop While: It’s the keyword to continue the loop and test the condition that you have specified.
  4. Condition: it is the condition that you want to test before the loop starts its second iteration and carries on the loop.

As you can see in the syntax of Do Loop While, it will first run the statement once and after that, it will go to the condition and test it, and if that condition is true, it will start the loop and continue it while the condition is true.

Example to Understand the DO Loop While

To understand the do loop while, let’s write a code to show an input box and ask the user to enter the password.

That input box will continue to show well the password entered by the user is incorrect up to the five attempts and after that, the input box will disappear without running the procedure.

  1. First, declare two variables that you need for storing the password and the counter for the attempts.
    7-declare-two-variables-you-need-for-storing
  2. After that, type the “Do” keyword. Here you don’t need to define the condition first as you have seen in the syntax.
    8-type-the-do-keyword
  3. Next, you need to write a line of code to show the input box that asks the user to enter the password.
    9-write-a-line-of-code
  4. From here, you need to define a counter that can count upto five (adds up with each interation of loop).
    10-define-a-counter
  5. Now, type the keyword “Loop While” and define two conditions that can verify the value entered by the user and into the input box and can test the value of the counter if it’s lower then than 5.
    11-type-keyword-loop-while-and-define-two-condition
  6. In the end, write the code that you want to run. Here I’m using the IF statement that will show a message box if the password entered by the user is correct.
    12-write-the-code-you-want-to-run
Sub vba_do_loop_while()

Dim varPassword As Variant, i As Double
Do
    varPassword = InputBox _
    ("Enter the password to start the procedure:", _
    "Check Password 1.0")   
    i = i + 1
Loop While varPassword <> "CorrectPassword" And i < 5
If varPassword = "CorrectPassword" Then
    MsgBox "Your Password is Correct"
End If

End Sub

Let me explain this code.

  • In the first part of this code, you have the do loop while which will show an input box to the user and ask for a password.
  • And if the password is incorrect it will continue to run the loop until the user enters the correct password.
  • But as you are using a counter to count the iterations of the loop and once that counter reach the 5, the loop will stop.

A Do…While loop is used when we want to repeat certain set of statements as long as the condition is true. The condition may be checked at the starting or at the end of the loop

Flowchart:

Uses of Do-While loop:

The Do While loop is used in two ways:

  • Do…while loop which checks the condition at the STARTING of the loop.
  • Do…while loop which checks the condition at the  END of the loop.

Syntax 1:

Do While condition
  [statements]
  [Exit Do]
  [statements]
Loop  

Syntax 2: 

Do While 
 [statements]
[Exit Do]
[statements]
Loop  condition

Implementing a Do While loop:

Follow the below steps to implement a Do-While loop:

Step 1: Define a Macro

Private Sub Demo_Loop()
End Sub

Step 2: Define variables

j=2
i=1

Step 3: Write Do While Loop. You can write condition at the beginning or at the end

Do While i < 5

Step 4: Write statements to be executed in loop

msgbox "Table of 2 is : " & (j*i)
     i=i+1

Step 5: End loop.

Now let’s take a look at some of the examples.

Example 1: Do…while loop which checks the condition at the STARTING of the loop. The below example uses Do…while loop to check the condition at the starting of the loop. The statements inside the loop are executed, only if the condition is True. We will print Table of 2 using Do…while loop;

Private Sub Demo_Loop()
        j=2
       i=1
      Do While i < 5
     msgbox "Table of 2 is : " & (j*i)
      i=i+1
      Loop
End Sub

Output:

Example 2: Do…while loop which checks the condition at the  END of the loop. The below example checks the condition at the end of the loop. The major difference between these two syntax is explained in the following example.

Private Sub Demo_Loop()
      i = 10
     Do
     i = i + 1
     MsgBox "The value of i is : " & i
  Loop While i < 3 'Condition is false.Hence loop is executed once.
End Sub

When the above code is executed, it prints the following output in a message box.

Output:

VBA Do While Loop

Excel VBA Do While Loop

Do While Loop means to do something while the condition is TRUE. It is like a logical function which works based on TRUE or FALSE. So if the condition is TRUE, it will keep executing the statement inside the loop, but if the condition is FALSE straight away, it will exit the Do While statement. The working of the VBA Do While Loop is shown in the figure given below.

VBA What is Do While Loop

Syntax of Do While Loop in VBA Excel

Do While Loop has two kinds of syntax in Excel VBA.

VBA Do While Syntax 1

VBA Do While Syntax 2

Both look very similar, and there is one simple differentiation in them.

In the first syntax “Do While” loop checks the condition first and gives the condition result is TRUE or FALSE. If the condition is TRUE, it will execute the code and perform a specified task, and if the condition is FALSE, then it will exit the loop.

In the second syntax “Do” loop firstly will execute the code, and then it tests whether the condition is TRUE or FALSE. If the condition is TRUE, it will again go back and perform the same task. If the condition is FALSE, then it will straight away exit the loop.

Example of Excel VBA Do While Loop

If you have not understood anything in the theory part nothing to worry about. I will explain to you the simple set of examples to have a fair knowledge about this loop.

You can download this VBA Do While Loop Excel Template here – VBA Do While Loop Excel Template

Now we will perform the task of inserting the first 10 serial numbers from cell A1 to A10. Follow the below steps to apply the “Do While” loop.

Step 1:

Create a macro name first.

Code:

Sub Do_While_Loop_Example1()

End Sub

VBA Do While Example 1

Step 2:

Define a variable as “Long”. I have defined “k” as a long data type.

Code:

Sub Do_While_Loop_Example1()

     Dim k As Long

End Sub

VBA Do While Example 1-2

Step 3:

Now enter the word “Do While”. And after starting the loop name, enter the condition as “k <=10”.

Code:

Sub Do_While_Loop_Example1()

     Dim k As Long

     Do While k <= 10

End Sub

VBA Do While Example 1-3

Step 4:

Now using the CELLS property, let’s insert serial numbers.

Code:

Sub Do_While_Loop_Example1()

  Dim k As Long

  Do While k <= 10
     Cells(k, 1).Value = k
End Sub

VBA Do While Example 1-4

Note: Here, variable “k” starts from 1, so at first k value is equal to 1. Wherever “k” is, there is equal to 1.

Step 5:

Now close the loop by entering the word “LOOP”.

Code:

Sub Do_While_Loop_Example1()

  Dim k As Long

  Do While k <= 10
     Cells(k, 1).Value = k
  Loop

End Sub

VBA Do While Example 1-5

Ok, we are done. For better understanding, let’s test this code one by one by pressing the F8 key once.

The first press F8 key, it will highlight the macro name by yellow color.

Example 1-6

Now one more time, press the F8 key; it will jump to Do While Loop. Place the cursor on “k” and see what the value is.

Example 1-7

So, K=0. The reason why “k” is equal to zero now because the loop is not started to executed here. Press F8 one more time and see what the value is.

Example 1-8

Still, the “k” value is zero. Ok, let’s do one thing now, stop the running of macro and assign the value of “k” as 1 before the loop starts.

Example 1-9

Now inside the loop, reassign the k value as k = k +1.

Example 1-10

Now start the process of executing the code line by line by pressing the F8 key. Start pressing the F8 and see what the value is when it executes the “Do While” loop.

Code:

Sub Do_While_Loop_Example1()

        Dim k As Long

k=1

        Do While k <= 10
Cells(k, 1).Value = k
k = k + 1

         Loop

End Sub

Example 1-11

So the “k” value is equal to 1. Wherever “k” is, there is equal to the value of 1. So the line of code Cells (k, 1). Value = k is equal to:

Cells (1, 1).Value = 1 i.e. Row 1 & Column 1 (A1 cell) value is equal to 1.

Press the F8 key and execute the action inside the loop.

Example 1-12

Now, look at the value in cell A1.

Example 1-13

So we got the value of 1 in cell A1.

Now execute the next line by pressing the F8 key and see what the value of “k” is.

Example 1-14

So now the k value is equal to 2. So wherever k is, there is equal to 2.

Press the F8 key; now, the code will return to test the value of k.

Example 1-15

Now press two more times the F8 key and see what the value is in cell A2.

Example 1-16

Like this, Do While Loop keeps executing the task of inserting serial numbers until the value of k reaches 11. Now I have already executed line by line until the k value becomes 10.

Example 1-17

Now, if I press one more time F8 key, it will go back to test the condition but will not execute the line of code because the k value is more than 10 now.

Example 1-18

If I press the F8 key, it will straight away exit the loop and goes to End Sub.

Example 1-19

The final output is given as follows.

Example 1-20

Like this, VBA Do While Loop can be used to perform the same set of tasks until the given condition is TRUE.

Things to Remember

  • VBA Do While Loop executes the task until the condition is TRUE.
  • We can also test the condition at the beginning of the loop or also at the end of the loop.
  • The movement condition is FALSE; it will exit the loop and will not perform the task.

Recommended Articles

This has been a guide to VBA Do While Loop. Here we discussed how to use Excel VBA Do While Loop along with some practical examples and a downloadable excel template. You can also go through our other suggested articles –

  1. VBA Function
  2. VBA XML
  3. VBA VLOOKUP
  4. VBA IsError
Skip to content

How to Use Do Until and Do While Loops in VBA

How to Use Do Until and Do While Loops in VBA: Step-by-Step

Written by co-founder Kasper Langmann, Microsoft Office Specialist.

Like for loops, do until and do while loops are powerful concepts that you’ll find in most programming languages.

They both belong to the “do loop” category in Excel. So, when you hear that reference, someone means either the do until loop or do while loop.

Both loops do a specified task inside the loop again and again until the loop ends♻️

Let me show you the do while and do until loops with some practical examples.

And I’ll pinpoint the differences between the two, so you know which loop in VBA that’s best for you.

If you want to tag along as you read this guide, please download the sample workbook here.

Using do loops in Excel VBA

Before we get into the specific syntax of the VBA do until loop, let’s talk about exactly what’s happening here.

Here’s a real-world example: if you have a spreadsheet full of first and last names in columns A and B, you might combine them, one by one, into column C. You’ll do this until all of the names have been combined.

In essence, after each combination, you ask yourself: “Are all of the names combined?” If the answer is no, you keep going. As soon as the answer is yes, you stop.

A do until loop works on the same principle.

Kasper Langmann, Co-founder of Spreadsheeto

The example spreadsheet linked above has a series of first names in column A and last names in column B.

Let’s write a loop in VBA to combine them into full names in column C👌🏼

Take a look at the below code. That’s the VBA do until loop that combines the content of cells.

The loop starts with the “Do Until” statement. Then, it’s specified when the loop should end. Then the loop executes all the actions, then the next loop runs, then it combines cells again, moves to the next loop, etc.

Sub combineNamesUntil()
i = 2
Do Until IsEmpty(Cells(i, 1))
Cells(i, 3).Value = Cells(i, 1) & " " & Cells(i, 2)
i = i +1
Loop
End Sub

The first code line establishes i as a counter variable. We’ll come to its function in a moment.

The second line starts the loop. A do until loop needs a statement that resolves to TRUE or FALSE⚙️

In this case, we’re using IsEmpty, which checks a specific cell to see if it’s empty; if that cell contains a value, it returns FALSE. If it doesn’t contain a value, it returns TRUE.

A do until loop keeps running until it gets a TRUE back from this statement.

This is important; a do while loop is the exact opposite, and it’s easy to mix them up.

Kasper Langmann, Co-founder of Spreadsheeto

The next code line is the command we want to run.

In our case, we’re setting the cell in row i and column 3 (represented as (i, 3)) equal to the value of the cells in (i, 1) and (i, 2) separated by a space.

As i increases, so does the row we’re looking at. That’s the function of the counter variable in this script.

The next line is very important; it raises the counter variable by one. Without this line, Excel will continue looking at the same row forever.

Finally, we tell Excel that the loop is over with “Loop.”

Here’s what happens when we run the loop on the first sheet in the example workbook:

vba-do-until-results

As you can see, the loop worked perfectly.

Most importantly, as soon as it detected a blank cell in column A, it stopped running.

Using do while loops in Excel VBA

A do while loop is almost exactly the same as a do until loop – there’s just one crucial difference.

This type of loop runs until the statement at the beginning resolves to FALSE.

It’s the opposite of do until in this manner, but everything else is the same.

Here’s how we’d write the same loop as above as a do while:

Sub combineNamesWhile()
 i = 2
 Do While Not IsEmpty(Cells(i, 1))
   Cells(i, 3).Value = Cells(i, 1) & " " & Cells(i, 2)
   i = i +1
   Loop
End Sub

As you can see from the above code, the only differences are to change “Do Until” to “Do While” and to enter “Not” in front of IsEmpty.

That “Not” is important. Because we’re checking for the TRUE/FALSE value from IsEmpty, we need to invert it to keep it working in the same way as the do until VBA loop.

If you run this loop on the example spreadsheet, you’ll see that it gets the same result😎

Let’s try something a little different with this loop. Take a look at the below code:

Sub combineNamesWhile()
 i = 2
 Do While Not IsEmpty(Cells(i, 1)) OR Not IsEmpty(Cells(i, 2))
   If IsEmpty(Cells(i, 1)) Then
     Cells(i, 3).Value = Cells(i, 2)
   ElseIf IsEmpty(Cells(i, 2)) Then
     Cells(i, 3).Value = Cells(i, 1)
   Else
     Cells(i, 3).Value = Cells(i, 1) & " " & Cells(i, 2)
   EndIf
   i = i +1
   Loop
End Sub

The main difference with this loop is that it has two conditions instead of just one. Here’s that clause:

Not IsEmpty(Cells(i, 1)) OR Not IsEmpty(Cells(i, 2))

In essence, the above code says that as long as (i, 1) or (i, 2) contains a value, the rest of the VBA loop will run. In the above example, It only stops when both cells are empty.

This lets us deal with rows that have a single name instead of two. Run the loop on the second sheet in the example workbook to see what happens:

do-while-results

Then, open the Visual Basic editor and step through the loop one step at a time by pressing F8.

See if you can work out how the conditionals work and why this particular version of the script is better for working with both first/last and single names.

Comparison: VBA do until loop vs do while loop

A do-while loop will keep running the instructions over and over, doing the same task again and again while a certain condition is true.

Which is quite similar to all VBA loops.

But…’

Once the condition is no longer true, the Excel VBA loop will stop. It’s like a runner who keeps running until they are tired and can’t run anymore🏃🏼‍♀️

The loop keeps going while the condition is true, just like the runner keeps running while they have energy.

On the other hand, a do-until loop is a little different. It will keep running the instructions until a specific condition is true.

It’s like a runner who keeps running until they cross the finish line. The loop keeps going until the condition is true, just like the runner keeps running until they cross the finish line.

Do you see the differences in these 2 examples?👀

So, in summary, a do-while loop keeps going while a certain condition is true, and a do-until loop keeps going until a certain condition is true. They’re both useful in different situations, and it’s important to understand how they work to use them effectively in programming.

That’s it – Now what?

In conclusion, do until and do while loops are powerful concepts that you can use to automate repetitive tasks in VBA.

Both loops can execute a specified task again and again until a condition is met. However, the main difference between them is the condition that controls the loop’s execution.

A do until loop in VBA runs until the condition is TRUE, while a do while loop runs until the condition is FALSE.

It’s essential to choose the right loop for the task at hand to avoid logical errors and optimize your code’s efficiency💡

By mastering the concepts of do until and do while loops, you can power up Excel and increase your productivity.

Loops are just one part of VBA programming as a whole. It’s important to understand the other parts like if statements, variables, and much more. If you want to learn the key concepts, check out my free 30-minute online course on Excel VBA here.

Kasper Langmann2023-02-21T09:34:21+00:00

Page load link

Содержание

  1. Do. Loop statement
  2. Syntax
  3. Remarks
  4. Example
  5. See also
  6. Support and feedback
  7. Использование Do. Операторы цикла
  8. Повторяющиеся инструкции, когда условие имеет значение True
  9. Повторяющиеся инструкции до тех пор, пока условие не станет true
  10. Выход из do. Оператор Loop из цикла
  11. См. также
  12. Поддержка и обратная связь
  13. Сделать. Оператор Loop
  14. Синтаксис
  15. Замечания
  16. Пример
  17. См. также
  18. Поддержка и обратная связь
  19. Оператор Do. Loop (Visual Basic)
  20. Синтаксис
  21. Компоненты
  22. Комментарии
  23. Выход из Do
  24. Пример 1
  25. Пример 2
  26. Пример 3
  27. Пример 4
  28. Все циклы VBA
  29. Краткое руководство по VBA While Loops
  30. Введение
  31. Цикл For против цикла Do While
  32. Условия
  33. Формат цикла Do
  34. Цикл Exit Do
  35. While Wend
  36. Бесконечный цикл
  37. Использование функций Worksheet вместо циклов
  38. Резюме

Do. Loop statement

Repeats a block of statements while a condition is True or until a condition becomes True.

Syntax

Do [< While | Until > condition ] [ statements ] [ Exit Do ] [ statements ] Loop

Or, you can use this syntax:

Do [ statements ] [ Exit Do ] [ statements ] Loop [< While | Until > condition ]

The Do Loop statement syntax has these parts:

Part Description
condition Optional. Numeric expression or string expression that is True or False. If condition is Null, condition is treated as False.
statements One or more statements that are repeated while, or until, condition is True.

Any number of Exit Do statements may be placed anywhere in the Do…Loop as an alternate way to exit a Do…Loop. Exit Do is often used after evaluating some condition, for example, If…Then, in which case the Exit Do statement transfers control to the statement immediately following the Loop.

When used within nested Do…Loop statements, Exit Do transfers control to the loop that is one nested level above the loop where Exit Do occurs.

Example

This example shows how Do. Loop statements can be used. The inner Do. Loop statement loops 10 times, asks the user if it should keep going, sets the value of the flag to False when they select No, and exits prematurely by using the Exit Do statement. The outer loop exits immediately upon checking the value of the flag.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Использование Do. Операторы цикла

Использовать Do. Операторы цикла для выполнения блока инструкций неограниченное количество раз. Операторы повторяются до тех пор, пока сохраняется условие True, или пока условие не станет True.

Повторяющиеся инструкции, когда условие имеет значение True

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

В следующей ChkFirstWhile процедуре необходимо проверить условие перед вводом цикла. Если myNum задано значение 9, а не 20, операторы внутри цикла никогда не будут выполняться. В процедуре ChkLastWhile инструкции в цикле выполняются только один раз, прежде чем условие станет False.

Повторяющиеся инструкции до тех пор, пока условие не станет true

Существует два способа использования ключевого слова Until для проверки условия в операторе Do. Loop. Вы можете проверить условие перед вводом цикла (как показано в ChkFirstUntil процедуре) или проверить его после выполнения цикла хотя бы один раз (как показано в процедуре ChkLastUntil ). Повторение циклов продолжается, пока сохраняется условие False.

Выход из do. Оператор Loop из цикла

Вы можете выйти из do. Выполните цикл с помощью инструкции Exit Do . Например, чтобы выйти из бесконечного цикла, используйте инструкцию Exit Do в блоке инструкции True либо if. Затем. Оператор Else или оператор Select Case . Если условие будет False, цикл запустится обычным образом.

В следующем примере myNum присваивается значение, которое создает бесконечный цикл. Оператор If. Then. Else проверяет это условие, а затем выходит из бесконечного цикла.

Чтобы остановить бесконечный цикл, нажмите клавиши ESC или CTRL+BREAK.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Сделать. Оператор Loop

Повторяет блок операторов, пока условие имеет значение True или пока условие не примет значение True.

Синтаксис

Do [< While | Until > condition ] [ statements ] [ Exit Do ] [ statements ] Loop

Также можно использовать следующий синтаксис.

Do [ инструкции ] [ Exit Do ] [ операторы ] Loop [< While | Until > condition ]

Синтаксис оператора Do Loop состоит из следующих элементов.

Part Описание
Состояние Необязательный параметр. Числовое выражение или строковое выражение, разрешаемое в значение True или False. Если выражение condition разрешается в значение Null, его значением считается False.
Операторы Один или несколько операторов, которые повторяются, пока условие condition имеет значение True или пока условие не примет это значение.

Замечания

Любое количество операторов Exit Do может быть размещено в любом месте в . Цикл в качестве альтернативного способа выхода из . Цикл. Выход Do часто используется после оценки какого-то условия, например если. Затем в этом случае оператор Exit Do передает управление инструкции сразу после цикла.

При использовании во вложенных циклах Do…Loop оператор Exit Do передает управление циклу, который находится на один уровень выше цикла оператора Exit Do.

Пример

В этом примере показано использование операторов Do. Loop. Внутреннее . Оператор Loop выполняет цикл 10 раз, запрашивает у пользователя, следует ли продолжать работу, устанавливает для флага значение False при выборе параметра Нет, а затем преждевременно завершает работу с помощью инструкции Exit Do . Выход из внешнего цикла происходит сразу после проверки значения флага.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Оператор Do. Loop (Visual Basic)

Повторяет блок инструкций, пока Boolean условие не станет True или не станет True .

Синтаксис

Компоненты

Термин Определение
Do Обязательный. Запускает определение Do цикла.
While Невозможно при Until использовании. Повторяйте цикл до тех пор, пока condition не будет False .
Until Невозможно при While использовании. Повторяйте цикл до тех пор, пока condition не будет True .
condition Необязательный элемент. Выражение Boolean . Если condition это так Nothing , Visual Basic обрабатывает его как False .
statements Необязательный элемент. Один или несколько операторов, повторяющихся в то время или до тех пор, condition является True .
Continue Do Необязательный элемент. Передает управление в следующую итерацию Do цикла.
Exit Do Необязательный элемент. Передает элемент управления из Do цикла.
Loop Обязательный. Завершает определение Do цикла.

Комментарии

Используйте структуру Do. Loop , если требуется повторять набор инструкций неограниченное количество раз, пока условие не будет выполнено. Если вы хотите повторить инструкции в заданное количество раз, параметр For. Следующий оператор обычно является лучшим выбором.

Можно использовать While один или несколько Until вариантов condition , но не оба. Если вы не предоставите ни разу, цикл продолжается до тех пор, пока Exit не будет передан элемент управления из цикла.

Вы можете проверить condition только один раз в начале или в конце цикла. Если тестироваться condition в начале цикла (в инструкции Do ), цикл может не выполняться даже один раз. При тестировании в конце цикла (в инструкции Loop ) цикл всегда выполняется по крайней мере один раз.

Условие обычно приводит к сравнению двух значений, но это может быть любое выражение, результатом которого является логическое значение типа данных ( True или False ). Сюда входят значения других типов данных, таких как числовые типы, преобразованные в Boolean .

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

Структура Do. Loop обеспечивает большую гибкость, чем while. Оператор End While , так как он позволяет решить, следует ли завершать цикл, когда condition он перестает быть True или когда он сначала становится True . Он также позволяет тестировать condition в начале или в конце цикла.

Выход из Do

Оператор Exit Do может предоставить альтернативный способ выхода Do…Loop из . Exit Do передает управление непосредственно оператору, следующему за оператором Loop .

Exit Do часто используется после оценки некоторых условий If. Then. Else , например в структуре. Может потребоваться выйти из цикла, если обнаруживается условие, которое делает его ненужным или невозможным продолжать итерацию, например ошибочное значение или запрос на завершение. Одним из способов Exit Do является проверка на условие, которое может вызвать бесконечный цикл, который является циклом, который может выполняться большое или даже бесконечное количество раз. Можно использовать для Exit Do экранирования цикла.

Вы можете включить любое количество Exit Do операторов в любом месте. Do…Loop

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

Пример 1

В следующем примере операторы в цикле продолжают выполняться до тех пор, пока index переменная не будет больше 10. Предложение Until находится в конце цикла.

Пример 2

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

Пример 3

В следующем примере цикл останавливается, condition если index переменная больше 100. Однако оператор If в цикле приводит Exit Do к остановке цикла, если переменная индекса больше 10.

Пример 4

В следующем примере считываются все строки в текстовом файле. Метод OpenText открывает файл и возвращает StreamReader объект, который считывает символы. В условии Do. Loop метод StreamReader определяет наличие Peek дополнительных символов.

Источник

Все циклы VBA

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

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

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

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

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

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

Краткое руководство по 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

Введение

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

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

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

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

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

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

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

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

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

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

Условия

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

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

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

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

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

Использование «=» Тип Имеется в виду
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 всегда в конце последней строки.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

While против Until

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

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

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

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

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

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

Примеры Until и While

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

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

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

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

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

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

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

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

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

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

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

Цикл Exit Do

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

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

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

While Wend

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

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

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

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

While Wend против Do

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Резюме

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

Цикл While Wend

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

Источник

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