Presentation is loading. Please wait.

Presentation is loading. Please wait.

“Going loopy with Visual Basic!” Presented by Robert Eadie.

Similar presentations


Presentation on theme: "“Going loopy with Visual Basic!” Presented by Robert Eadie."— Presentation transcript:

1 “Going loopy with Visual Basic!” Presented by Robert Eadie

2 Introduction In 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: Visual Basic supports the following loop structures: 1. Do While...Loop 2. Do Until...Loop 3. Do…Loop While 4. Do…Loop Until 5. For…Next6. For Each…Next Open Closed

5 1. Do While…Loop Use 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 condition statement-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 = 1 Do While InStr(position, longstring, target) 'Returns True/False position = InStr(position, longstring, target) + 1 Count = Count + 1 Loop CountStrings = Count End Function

8 2. Do Until…Loop Use 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 condition statement-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 = vbNo ProcessUserData 'Call procedure to process data ProcessUserData 'Call procedure to process data Response = MsgBox("Do you want to process more data?", vbYesNo) Response = MsgBox("Do you want to process more data?", vbYesNo)Loop

10 Summary Both 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 While When 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-block Loop While condition

12 3.1 Do…Loop While In 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 Then first = c.Address Do c.Font.ColorIndex = 5 Set c = rSearch.FindNext(c) Loop While (Not c Is Nothing) And (c.Address <> first) Else MsgBox "not found“ End If End Sub

14 4. Do…Loop Until With 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-block Loop Until condition

15 4.1 Do…Loop Until Do ProcessUserData 'Call procedure to process data ProcessUserData 'Call procedure to process data response = MsgBox("Do you want to process more data?", vbYesNo) response = MsgBox("Do you want to process more data?", vbYesNo) Loop Until response = vbNo

16 Summary Both 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 Summary As 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…Next When 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] For counter = startvalue To endvalue [Step stepvalue]statement-block Next [counter] Next [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…Next In 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…Next 4. Increments counter by the amount specified with the stepvalue. If the stepvalue argument is omitted, counter is incremented by 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…Next The 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 numBeeps Beep Next counter End Sub

23 5.5 For…Next Because 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…Next In 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 2 ArrayToClear(i) = 0 Next i End Sub

25 6. For Each…Next A 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-block Next element Next element

27 6.2 For Each…Next When Visual Basic runs a For Each…Next loop, it follows these steps: 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 It defines element as naming the first element in group (provided that there’s at least one element).

28 6.3 For Each…Next The 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.Cells If c.Value < -1 Then c.Font.ColorIndex = 3 Next c

29 6.4 For Each…Next Keep 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 !! ToUse Test a condition at the start of the loop, run the loop only if the condition is True, and continue until the condition becomes False Do While…Loop

31 Quick Quiz !! ToUse Test a condition at the start of the loop, run the loop only if the condition is False, and continue until the condition becomes True Do Until…Loop

32 Quick Quiz !! ToUse Always 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 False Do…Loop While

33 Quick Quiz !! ToUse Always 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 True Do…Loop Until

34 Quick Quiz !! ToUse Run 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 loop For…Next

35 Quick Quiz !! ToUse Run a loop once for each object in a collection For Each…Next


Download ppt "“Going loopy with Visual Basic!” Presented by Robert Eadie."

Similar presentations


Ads by Google