《(10.5.1)--8.5For...NextStatements.ppt》由会员分享,可在线阅读,更多相关《(10.5.1)--8.5For...NextStatements.ppt(10页珍藏版)》请在得力文库 - 分享文档赚钱的网站上搜索。
1、For.Next Loop数据库技术与程序设计Loop StructureWhile programming,we often facing a situation where a While programming,we often facing a situation where a repeated execution is always needed.repeated execution is always needed.The Loop Structure can meet the demands.The Loop Structure can meet the demands.The
2、 Loop Structure The Loop Structure can control the repeated execution of a can control the repeated execution of a certain part of the statements sequence in the program by certain part of the statements sequence in the program by specifiying the current value of the given conditions.specifiying the
3、 current value of the given conditions.数据库技术与程序设计Loop Structure VBA provides four loop statements:,which are:Do While.LoopDo While.LoopFor.NextFor.NextWhile.WendWhile.WendDo Until.LoopDo Until.Loop数据库技术与程序设计ForNext StatementForNext Loop is also called numeric for-loops.SyntaxFor =To Step statements
4、Exit For statementsNext counterExecution:the VBA will first calculate the counters start,end and step as well as assign initial value to the counter.Then it compares the counter(assigned value already)with end.If the counter is less than end(only if step is positive or 0),or more than/equal to end(o
5、nly if step negative),the VBA will execute the statements between For and Next,namely the loop.The counter will automatically add a value of step wherever it encounters Next and compares itself with end again.The loop constantly repeats itself again and again and will not stop until value in the cou
6、nter exceeds end.counter=start statementscounter=counter+stepcounter start数据库技术与程序设计ForNext StatementExampleOutputting four“*”in one line in Immediate Window,which can be achieved by following program.Public Sub example1()Dim i As IntegerFor i=1 To 4 Step 1Debug.Print*;Adding“;”after output statemen
7、t means the next output will follow the same line as the former instead of beginning a new line.NextDebug.Print EndEnd Sub数据库技术与程序设计ForNext Statement数据库技术与程序设计ForNext StatementExampleRewrite the statements above so as to output strings“1 2 3 4”in only one line in Immediate Window.This statement can
8、be achieved by the following program:Public Sub example2()Dim i As IntegerFor i=1 To 4 Step 1Debug.Print i;Note:add“;”at the end of the output statement.NextDebug.Print endEnd Sub数据库技术与程序设计ForNext Statement数据库技术与程序设计ForNext StatementQuestion:Find the largest integer within 100 which is divisible by
9、7.(Use For Next Statement)Attention:Loop from the minimum to maximum,or conversely?Step can be a negative.Exit For Provides an immediate way to exit a For Loop数据库技术与程序设计ForNext StatementPublic Sub example3()Dim n As Integer For n=100 To 1 Step-1 If n Mod 7=0 Then Debug.Print n Exit For End If NextEnd Sub