“Going loopy with Visual Basic!”

Slides:



Advertisements
Similar presentations
Modeling using VBA. Covered materials -Userforms -Controls -Module -Procedures & Functions -Variables -Scope.
Advertisements

CS0004: Introduction to Programming Repetition – Do Loops.
Visual Basic.NET BASICS Lesson 10 Do Loops. 2 Objectives Explain what a loop is. Use the Do While and Do Until loops. Use the InputBox function. Use the.
Repeating Actions While and For Loops
Do/Loops A loop repeats a series of instructions. An iteration is a single execution of the statement(s) in the loop. Used when the exact number of iterations.
Slide 1 VB Program Flow Control. Slide 2 Making Decisions v Decision Statement: control the execution of parts of the program based on conditions. v The.
Iteration (Looping Constructs in VB) Iteration: Groups of statements which are repeatedly executed until a certain test is satisfied Carrying out Iteration.
Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Repeating Program Instructions Chapter Microsoft Visual Basic.NET: Reloaded 1.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 03.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
Exploring Microsoft Excel 2002 Chapter 8 Chapter 8 Automating Repetitive Tasks: Macros and Visual Basic for Applications By Robert T. Grauer Maryann Barber.
Python quick start guide
Repetition Statements Repeating an Action A specified number of times While a Condition is True Until a Condition is True.
Fundamentals of C and C++ Programming Control Structures and Functions.
Lecture Set 5 Control Structures Part D - Repetition with Loops.
CIS 115 Lecture 8. There are 3 control structures common to most computer languages that determine the flow, or path of execution, of the code:  Sequential.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
CPS120 Introduction to Computer Science Iteration (Looping)
Arrays and 2D Arrays.  A Variable Array stores a set of variables that each have the same name and are all of the same type.  Member/Element – variable.
PHP Conditional Statements Conditional statements in PHP are used to perform different actions based on different conditions. Conditional Statements Very.
1 Week 6 The Repetition Structure. 2 The Repetition Structure (Looping) Lesson A Objectives After completing this lesson, you will be able to:  Code.
Repetition Statements.  Often it is necessary to repeat statements many times  Java has two ways of doing this  while statements  for statements.
1 INF110 Visual Basic Programming AUBG Spring semester 2011 Reference books: Schneider D., An Introduction to Programming Using Visual Basic, Prentice.
Compunet Corporation1 Programming with Visual Basic.NET While, Do and For – Next Loops Week 5 Tariq Ibn Aziz.
Chapter 6: The Repetition Structure
Tutorial 51 Programming Structures Sequence - program instructions are processed, one after another, in the order in which they appear in the program Selection.
Tutorial 6 The Repetition Structure
Chapter 4 Looping Statements Adapted From: Starting Out with Visual Basic 2008 (Pearson)
Visual Basic.net Loops. Used to do multiple executions of the same block of code Do while loops Do until loops For next loops.
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
Lab 4 Range Review, Control Logic and Loops ► Range Review ► Control Logic and Loops ► Exercise.
COMPUTER PROGRAMMING II SUMMER 2011 Visual Basic to C#
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Introduction to Problem Solving and Control Statements.
JavaScript, Fourth Edition
1 Chapter 9. To familiarize you with  Simple PERFORM  How PERFORM statements are used for iteration  Options available with PERFORM 2.
1 Scripting Languages VBScript - Recognized mainly by Internet Explorer only - Netscape does have a plug-in JavaScript - Recognized by Internet Explorer.
CPS120 Introduction to Computer Science Iteration (Looping)
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
For…Next and Do...While Loops! Happy St. Patrick’s Day!
Controlling Program Flow with Looping Structures
5.1 Introduction Problem Solving –Requires understanding of: Building blocks Program-construction principles BZUPAGES.COM.
Lab 6 (1) Range Review, Control Logic and Loops ► Control Logic and Loops ► Exercise.
Flow Control in Imperative Languages. Activity 1 What does the word: ‘Imperative’ mean? 5mins …having CONTROL and ORDER!
CSET 3250 Client-Side Scripting VBScript : Operators, Control Structures, Procedures and Functions.
Dani Vainstein1 VBScript Session 5. Dani Vainstein2 What we learn last session? Branching Branching using If … Then … Else statement. Branching using.
© 2006 ITT Educational Services Inc. Introduction to Computer Programming: Unit 9: Chapter 5: Slide 1 Unit 9 Do Until and For… Next Loops Chapter 5 Lists,
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
Chapter 5 - VB 2008 by Schneider1 Chapter 5 – Repetition 5.1 Do Loops 5.2 Processing Lists of Data with Do Loops 5.3 For...Next Loops.
Loops causes program to execute the certain block of code repeatedly until some conditions are satisfied. Suppose you want to execute some code/s 10 times.
UNIT 5 Lesson 15 Looping.
VBA - Excel VBA is Visual Basic for Applications
Problem Solving and Control Statements: Part 2
Warm-up Program Use the same method as your first fortune cookie project and write a program that reads in a string from the user and, at random, will.
Lists, Loops, Validation, and More
Control Structures: Part 2
JavaScript: Control Statements.
Iteration: Beyond the Basic PERFORM
CIS 16 Application Development Programming with Visual Basic
Do … Loop Until (condition is true)
Introduction to Problem Solving and Control Statements
Prepared By: Deborah Becker
ASP control structure BRANCHING STATEMENTS
Presentation transcript:

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

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.

“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.

Types of loop in Visual Basic Visual Basic supports the following loop structures:  Open 1. Do While...Loop 3. Do…Loop While 2. Do Until...Loop 4. Do…Loop Until Closed 5. For…Next 6. For Each…Next

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-block Loop

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.

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

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-block Loop

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 Loop

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.

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: Do statement-block Loop While condition

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.

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

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: Do statement-block Loop Until condition

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

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.

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.

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.

5.1 For…Next The general format is: For counter = startvalue To endvalue [Step stepvalue] statement-block 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.

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.

5.3 For…Next 4. 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.

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

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.

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

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.

6.1 For Each…Next The general format is: For Each element In group statement-block Next element

6.2 For Each…Next When 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.

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

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.

Quick Quiz !! To Use 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

Quick Quiz !! To Use 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

Quick Quiz !! To Use 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

Quick Quiz !! To Use 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

Quick Quiz !! To Use 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

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