Several examples of VBA do loop

Source: Internet
Author: User

One, do ... Syntax for loop statements

Do[while I until< logical expression;

< circulation body >

Loop[while I until< logical expression;

When the value of the logical expression is true, the loop body is executed using the While keyword, until the logical expression evaluates to false and jumps out of the loop body, that is, the Do While-loop loop statement is executed.

When the value of the logical expression is false, the Until keyword executes the loop body until the logical expression's value is true to jump out of the loop body, that is, to execute the Do Until-loop loop statement.

In most cases doing while. Loop loop statements and do Until-loop loop statements can be used interchangeably, simply reverse the loop condition. However, for some operations that need to be judged before they are performed, it is best to use the Do While-loop loop statement.

In addition, when using the Do-loop loop statement, you need to use the "Exit do" statement in the loop body to jump out of the Do-loop loop and execute a statement following the loop.

Ii. a few examples of do...loop

① Example

Dim mycnt as Long

mycnt = 1

Do While mycnt <= 5

Cells (mycnt, 3). Value = Cells (mycnt, 1). Value * Cells (mycnt, 2). Value

mycnt = mycnt + 1

Loop

When the mycnt is less than or equal to 5 o'clock, the loop is exited.

② Example

Dim mycnt as Long

mycnt = 1

Todo

Cells (mycnt, 3). Value = Cells (mycnt, 1). Value * Cells (mycnt, 2). Value

mycnt = mycnt + 1

Loop while mycnt<=5

③ Example

Dim mycnt as Long

mycnt = 1

Todo

Cells (mycnt, 3). Value = Cells (mycnt, 1). Value * Cells (mycnt, 2). Value

mycnt = mycnt + 1

If mycnt>5 Then Exit do

Loop

④ Example

Counter = 0

MyNum = 9

Do Until MyNum = 10

MyNum = myNum-1

Counter = counter + 1

If MyNum < Then Exit do

Loop

MsgBox "The Loop Made" & Counter & "repetitions."

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.