Presentation on theme: "“Going loopy with Visual Basic!”"— Presentation transcript:
1 “Going loopy with Visual Basic!” Presented byRobert Eadie
2 IntroductionIn the following set of slides, I will present the most common looping structures used in Visual Basic along with examples of their use and pitfalls to avoid.
3 “What is a loop?”Loop statements allow you to execute one or more lines of code repetitively. Many tasks consist of trivial operations that must be repeated, so looping structures are an important part of any programming language.
4 Types of loop in Visual Basic Visual Basic supports the following loop structures: Open1. Do While...Loop3. Do…Loop While2. Do Until...Loop4. Do…Loop UntilClosed5. For…Next6. For Each…Next
5 1. Do While…LoopUse the Do While...Loop statement when you want to test a condition before you run the loop and then continue to run the loop while the condition is True.The general format is:Do While conditionstatement-blockLoop
6 1.2 Do While…Loop Example: The Function procedure in the following slide counts the occurrences of a target string within another string by looping as long as the target string is found. Because the test is at the beginning of the loop, the loop runs only if the string contains the target string.
7 1.3 Do While…Loop Function CountStrings(longstring, target) position = 1Do While InStr(position, longstring, target) 'Returns True/Falseposition = InStr(position, longstring, target) + 1Count = Count + 1LoopCountStrings = CountEnd Function
8 2. Do Until…LoopUse the Do Until…Loop statement if you want to test the condition at the beginning of the loop and then run the loop until the test condition becomes True. If the condition is initially True, the statements inside the loop never run.The general format is:Do Until conditionstatement-blockLoop
9 2.2 Do Until…Loop Look at the example below. With the test at the beginning of the loop, the loop won't run if Response is equal to vbNo.Response = MsgBox("Do you want to process more data?", vbYesNo)Do Until Response = vbNoProcessUserData 'Call procedure to process dataLoop
10 SummaryBoth the Do While…Loop and Do Until…Loop are known as “pre-test” loops because the condition is tested before the loop is executed.This means that the loop may never be executed if the condition is not true the first time it is checked.In such a case, the program bypasses the loop and continues with the next instruction.
11 3. Do…Loop WhileWhen you want to make sure that the statements in a loop will run at least once, use Do…Loop While to put the test at the end of the loop. The statements will run as long as the condition is True.The general format is:Dostatement-blockLoop While condition
12 3.1 Do…Loop WhileIn the following Microsoft Excel example, the loop runs only if the Find method finds a cell that contains "test.“If the text is found, the loop sets the color of the cell, and then searches for the next instance of "test.“If no other instance is found, the loop ends.
13 3.2 Do…Loop While Sub MakeBlue() Set rSearch = Worksheets("sheet1").Range("a1:a10")Set c = rSearch.Find("test")If Not c Is Nothing Thenfirst = c.AddressDoc.Font.ColorIndex = 5Set c = rSearch.FindNext(c)Loop While (Not c Is Nothing) And (c.Address <> first)ElseMsgBox "not found“End IfEnd Sub
14 4. Do…Loop UntilWith the Do…Loop Until statement, which puts the test at the end of the loop, the loop runs at least once and stops running when the condition becomes True.The general format is:Dostatement-blockLoop Until condition
15 4.1 Do…Loop Until Do ProcessUserData 'Call procedure to process data response = MsgBox("Do you want to process more data?", vbYesNo)Loop Until response = vbNo
16 SummaryBoth the Do…Loop While and Do…Loop Until are known as “post-test” loops because the condition is not tested until after the first execution of the loop.This ensures that the loop will be executed at least once.
17 SummaryAs stated at the beginning, the loops covered so far are known as “open loops” in that the number of times the loop will be executed is not known at runtime.
18 5. For…NextWhen you know that you must run the statements a specific number of times, use a For...Next loop.Unlike the many variations of Do…Loop, a For...Next loop uses a counter variable that increases or decreases in value during each repetition of the loop.Whereas the variations of Do…Loop end when a test condition becomes True or False, a For...Next loop ends when the counter variable reaches a specified value.
19 5.1 For…Next The general format is: For counter = startvalue To endvalue [Step stepvalue]statement-blockNext [counter]Note:The variable name after the Next statement is optional, but it can make you code easier to read, especially if you have several nested For…Next loops.
20 5.2 For…NextIn executing the For…Next loop, Visual Basic does the following:1. Sets the counter equal to startvalue.2. Tests to see if counter is greater than endvalue. If so, it exits the loop. If stepvalue is negative, VB test to see if counter is less than endvalue, in which case it exits the loop.3. Executes the statement-block.
21 5.3 For…Next4. Increments counter by the amount specified with the stepvalue. If the stepvalue argument is omitted, counter is incremented by 1.5. Repeats steps 2 through 4.Note:The stepvalue argument can be either positive or negative. If startvalue is greater than endvalue, the stepvalue must be negative. If not, the loop’s body will not be executed, not even once.
22 5.4 For…NextThe Sub procedure in the following example sounds a tone however many times you specify.Sub BeepSeveral()numBeeps = InputBox("How many beeps?")For counter = 1 To numBeepsBeepNext counterEnd Sub
23 5.5 For…NextBecause it wasn’t specified otherwise, the counter variable in the preceding example increases by 1 each time the loop repeats.You can use the Step keyword to specify a different increment for the counter variable.If you specify a negative number, the counter variable decreases by the specified value each time through the loop.
24 5.6 For…NextIn the following Sub procedure, which replaces every other value in an array with 0 (zero), the counter variable increases by 2 each time the loop repeats.Sub ClearArray(ByRef ArrayToClear())For i = LBound(ArrayToClear) To UBound(ArrayToClear) Step 2ArrayToClear(i) = 0Next iEnd Sub
25 6. For Each…NextA For Each...Next loop is similar to a For...Next loop, except that it repeats a group of statements for each element in a collection of objects or in an array, instead of repeating the statements a specified number of times.This is especially useful if you don't know how many elements are in a collection, or if the contents of the collection might change as your procedure runs.
26 6.1 For Each…Next The general format is: For Each element In group statement-blockNext element
27 6.2 For Each…NextWhen Visual Basic runs a For Each…Next loop, it follows these steps:1. It defines element as naming the first element in group (provided that there’s at least one element).2. It runs through the statement-block.3. It tests to see whether element is the last element in group. If so, Visual Basic exits the loop.4. It defines element as naming the next element in group.5. It repeats steps 2 through 4.
28 6.3 For Each…NextThe following Microsoft Excel example examines each cell in the current region for cell A1 on the worksheet named "Sheet3" and formats its contents as red if its value is less than – 1.For Each c In Worksheets("sheet3").Range("a1").CurrentRegion.CellsIf c.Value < -1 Then c.Font.ColorIndex = 3Next c
29 6.4 For Each…NextKeep the following restrictions in mind when using the For Each...Next statement:1. For collections, element can only be a Variant variable, a generic Object variable, or a specific object type in a referenced object library. For arrays, element can only be a Variant variable.2. You cannot use the For Each...Next statement with an array of userdefined types, because a Variant variable cannot contain a userdefined type.
30 Quick Quiz !!To UseTest a condition at the start of the loop, run the loop only if the condition is True, and continue until the condition becomes FalseDo While…Loop
31 Quick Quiz !!To UseTest a condition at the start of the loop, run the loop only if the condition is False, and continue until the condition becomes TrueDo Until…Loop
32 Quick Quiz !!To UseAlways run the loop once, test a condition at the end of the loop, continue while the condition is True, and stop when the condition becomes FalseDo…Loop While
33 Quick Quiz !!To UseAlways run the loop once, test a condition at the end of the loop, continue while the condition is False, and stop when the condition becomes TrueDo…Loop Until
34 Quick Quiz !!To UseRun a loop a set number of times, using a loop counter that starts and ends at specified values and that changes value by a specified amount each time through the loopFor…Next
35 Quick Quiz !! To Use Run a loop once for each object in a collection For Each…Next