VBA Brush Up 06:Repeating Actions in VBA

來源:互聯網
上載者:User
Technorati 標籤: VBA,loop,for,while,do

來自:Julitta Korol,“Access.2003.Programming.by.Example.with.VBA.XML.and.ASP”,by Wordware Publishing, Inc. 2005, p91-p101

(1)Using the Do…While Loop

  1. Do While condition 
  2.     statement1 
  3.     statement2 
  4.     statementN 
  5. Loop

(2)continuously display an input box until the user enters the correct password

  1. Do While pWord <> "DADA" 
  2.     pWord = InputBox("What is the Report password?") 
  3. Loop

(3)Another Approach to the Do…While Loop

  1. Do 
  2.     statement1 
  3.     statement2 
  4.     statementN 
  5. Loop While condition

When you test the condition at the bottom of the loop, the statements inside the loop are executed at least once.

(4)Infinite Loops:

  1. Sub SayHello() 
  2.     Do 
  3.         MsgBox "Hello." 
  4.     Loop 
  5. End Sub

To stop the execution of the infinite loop, you must press Ctrl+Break. When Visual Basic displays the message box “Code execution has been interrupted,”click End to end the procedure.

(5)Do…Until repeats a block of code as long as something is false.

  1. Do Until condition 
  2.     statement1 
  3.     statement2 
  4.     statementN 
  5. Loop

(6)

  1. Do 
  2.     statement1 
  3.     statement2 
  4.     statementN 
  5. Loop Until condition

If you want the statements to execute at least once, no matter what the value of the condition, place the condition on the line with the Loop statement.

(7)

  1. For counter = start To end [Step increment] 
  2.     statement1 
  3.     statement2 
  4.     statementN 
  5. Next [counter]

(8)

  1. For Each element In Group 
  2.     statement1 
  3.     statement2 
  4.     statementN 
  5. Next [element]

Element is a variable to which all the elements of an array or collection will be assigned. This variable has to be of the Variant data type for an array and of the Object data type for a collection. Group is a name of a collection or an array.

(9)Exiting Loops Early: Exit For, Exit Do, Exit Sub, Exit Function.

(10)When writing nested loops, you must make sure that each inner loop is completely contained inside the outer loop. Also, each loop has to have a unique counter variable.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.