Control Statements Making Decision in Your Program.

Slides:



Advertisements
Similar presentations
TE Sessions Supported by: Basic Concepts of Programming November 3, 2012.
Advertisements

ISOM3230 Business Applications Programming
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
COMPUTER PROGRAMMING I Essential Standard 5.02 Understand Breakpoint, Watch Window, and Try And Catch to Find Errors.
AE6382 VBA - Excel l VBA is Visual Basic for Applications l The goal is to demonstrate how VBA can be used to leverage the power of Excel u VBA syntax.
Tutorial 12: Enhancing Excel with Visual Basic for Applications
Flow Charts, Loop Structures
CS0004: Introduction to Programming Repetition – Do Loops.
Programming in Visual Basic
Chapter 10 Introduction to Arrays
Trapping Errors and Debugging Code. Programming errors can vary by … Type Cause Effect Severity Other factors Error types Include Syntax Logic Compile.
Iteration (Looping Constructs in VB) Iteration: Groups of statements which are repeatedly executed until a certain test is satisfied Carrying out Iteration.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Input Validation Check the values entered into a text box before beginning any calculations Validation is a form of ‘self-protection’, rejecting bad data.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
5.05 Apply Looping Structures
Repetition Statements Repeating an Action A specified number of times While a Condition is True Until a Condition is True.
IE 212: Computational Methods for Industrial Engineering
Saeed Ghanbartehrani Summer 2015 Lecture Notes #4: Working with Variables and User Interfaces IE 212: Computational Methods for Industrial Engineering.
Visual Basic: An Object Oriented Approach 5: Structured Programming.
1 Visual Basic for Applications (VBA) for Excel Prof. Yitzchak Rosenthal.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
Chapter 17: Arrays Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Copyright © 2008 Pearson Prentice Hall. All rights reserved. 1 Microsoft Office Excel Copyright © 2008 Pearson Prentice Hall. All rights reserved
Class 3 Programming in Visual Basic. Class Objectives Learn about input/output Learn about strings Learn about subroutines Learn about arrays Learn about.
08/10/ Iteration Loops For … To … Next. 208/10/2015 Learning Objectives Define a program loop. State when a loop will end. State when the For.
COIT29222 Structured Programming Slide 1 COIT29222-Structured Programming Lecture Week 06  Reading: Study Guide Book 2, Modules 9 & 10 Textbook (4 th.
VB Core II Conditional statements Exception handling Loops Arrays Debugging.
ME 142 Engineering Computation I Debugging Techniques.
Input Textboxes Input Boxes Different than textboxes Good for small amount of input (form full of textboxes is not nice) X = Inputbox(“prompt message”,
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
MS Visual Basic Applications Walter Milner. Event-driven programming Standard approach for GUIs Contrast with old character interfaces – program determines.
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
‘Tirgul’ # 3 Enterprise Development Using Visual Basic 6.0 Autumn 2002 Tirgul #3.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
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.
Overview of VBA Programming & Syntax. Programming With Objects u Objects –Properties: attributes or characteristics of an object (e.g., font size, color,
259 Lecture 11 Spring 2013 Advanced Excel Topics – Loops.
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Spreadsheet Models for Managers: Session 14 14/1 Copyright © Richard Brenner Spreadsheet Models for Managers Session 14 Using Macros II Function.
JavaScript, Fourth Edition
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)
CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures.
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
Chapter 6 Looping Structures. Do…LoopDo…Loop Statement Can operate statements repetitively Do intx=intx + 1 Loop While intx < 10 –The Loop While operates.
Visual Basic Objects / Properties / Methods PropertyAdjective ObjectNoun Part of the application Attribute MethodVerb Action to do something.
31/01/ Selection If selection construct.
For…Next and Do...While Loops! Happy St. Patrick’s Day!
Controlling Program Flow with Looping Structures
Intro to Loops 1.General Knowledge 2.Two Types of Loops 3.The WHILE loop 1.
Controlling Program Flow with Decision Structures.
Input Boxes, List Boxes, and Loops Chapter 5. 2 Input Boxes Method for getting user’s attention to obtain input. InputBox() for obtaining input MessageBox()
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Loop Blocks Chapter 6 Part A. Program Blocks 1.Actions- commands, messages, methods 2.Branches- decisions to be made 3.Loops- actions to be repeated.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
1 Visual Basic for Applications - VBA IE What is VBA?  VBA comes with Office u Objects (e.g. of Excel) are exposed for use by VBA u Visual Basic.
Financial Information Management VB, VBA, VS, VSTO & VBE: Putting it all together Source: Excel VBA Programming by John Walkenbach.
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
Chapter 6 Controlling Program Flow with Looping Structures.
© 2010 Lawrenceville Press Slide 1 Chapter 5 The Do…Loop Statement  Loop structure that executes a set of statements as long as a condition is true. 
COMPREHENSIVE Excel Tutorial 12 Expanding Excel with Visual Basic for Applications.
VBA - Excel VBA is Visual Basic for Applications
VBA - Excel VBA is Visual Basic for Applications
ME 142 Engineering Computation I
Outline Altering flow of control Boolean expressions
Do … Loop Until (condition is true)
Presentation transcript:

Control Statements Making Decision in Your Program

If...Then...Else Statement (1) You can make decision by using the If...Then...Else statement. Syntax: If Condition1 Then Statements [ ElseIf Condition2 Then Statements ] [ Else Statements ] End If You can have more than one ElseIf.

If...Then...Else Statement (2) Function PressureWaring(Pressure) ' Give a warning message when vessel pressure is too high If Pressure > 10 Then MsgBox ("Pressure is extremely high! Process halt!") End If End Function

If...Then...Else Statement (3) Function PressureWaring(Pressure) ' Give a warning message when vessel pressure is too high If Pressure > 10 Then MsgBox ("Pressure is extremely high! Process halt!") Else MsgBox ("Okay") End If End Function

If...Then...Else Statement (4) Function PressureWaring(Pressure) ' Give a warning message when vessel pressure is too high or ' too low If Pressure > 10 Then MsgBox ("Pressure is extremely high! Process halt!") ElseIf Pressure < 1 Then MsgBox ("Pressure is extremely low!") Else MsgBox ("Okay") End If End Function

For Loop (1) For loop is used for the case with well known number of iteration. Syntax: For counter = start To end [ Step StepSize ] Statements Next [ counter ]

For Loop (2) Function CellGrowth(InitialBiomass, GrowthRate) Dim i, Biomass, NewBiomass Biomass = InitialBiomass For i = 1 To 10 NewBiomass = Biomass * GrowthRate Biomass = Biomass + NewBiomass Next i CellGrowth = Biomass End Function

For Loop (3) Be aware of infinite looping as a program bug: Function CellGrowth(InitialBiomass, GrowthRate) Dim i, Biomass, NewBiomass Biomass = InitialBiomass For i = 1 To 10 Step -1 NewBiomass = Biomass * GrowthRate Biomass = Biomass + NewBiomass Next i CellGrowth = Biomass End Function

For Loop (4) If you need to exit the For loop before you reach the ending condition, you can use the Exit For statement: For counter = start To end [ Step StepSize ] Statements If (ExitCondition) Then Exit For End If Next [ counter ]

Do While Loop (1) Do While loop is used for the case that the number of iterations is not well known. Syntax: Do While LoopingCondition Statements Loop Note that, if the looping condition is not True in before the Do While loop is executed, this Do While loop will not be executed.

Do While Loop (2) Function CellGrowth(InitialBiomass, GrowthRate) Dim i, Biomass, NewBiomass Biomass = InitialBiomass Do While Biomass <= NewBiomass = Biomass * GrowthRate Biomass = Biomass + NewBiomass Loop CellGrowth = Biomass End Function

Do While Loop (3) Be aware of infinite looping as a program bug: Function CellGrowth(InitialBiomass, GrowthRate) Dim i, Biomass, NewBiomass Do While Biomass <= NewBiomass = Biomass * GrowthRate Biomass = Biomass + NewBiomass Loop CellGrowth = Biomass End Function

Do While Loop (4) To avoid an unending iteration of the Do While loop, you can add a counter to stop it and exit the Do While loop with the Exit Do statement: counter = 0 Do While condition Statements counter = counter + 1 If (counter > LoopingLimit) Then Exit Do End If Loop

Do While Loop (5) Function CellGrowth(InitialBiomass, GrowthRate) Dim i, Biomass, NewBiomass Biomass = InitialBiomass i = 0 Do While Biomass < NewBiomass = Biomass * GrowthRate Biomass = Biomass + NewBiomass i = i + 1 If (i > 100) Then Exit Do End If Loop CellGrowth = Biomass End Function

Do While Loop (6) An alternative way to write the above code: counter = 0 Do While ((condition) AND (counter <= LoopingLimit)) Statements counter = counter + 1 Loop Do While loop with a counter is similar to the For loop.

Do Until Loop (1) Do Until loop is used for the case that the number of iterations is not well known. Syntax: Do Until ExitCondition Statements Loop Note that the statements within the loop will be executed until the ExitCondition is True. To avoid an unending iteration of the Do Until loop, you can add a counter to stop it and exit the Do Until loop with the Exit Do statement.

Do Until Loop (2) Function CellGrowth(InitialBiomass, GrowthRate) Dim i, Biomass, NewBiomass Biomass = InitialBiomass Do Until Biomass > NewBiomass = Biomass * GrowthRate Biomass = Biomass + NewBiomass Loop CellGrowth = Biomass End Function

Do Until Loop (3) Function CellGrowth(InitialBiomass, GrowthRate) Dim i, Biomass, NewBiomass Do While Biomass <= NewBiomass = Biomass * GrowthRate Biomass = Biomass + NewBiomass Loop CellGrowth = Biomass End Function Function CellGrowth(InitialBiomass, GrowthRate) Dim i, Biomass, NewBiomass Biomass = InitialBiomass Do Until Biomass > NewBiomass = Biomass * GrowthRate Biomass = Biomass + NewBiomass Loop CellGrowth = Biomass End Function

Do Loop Until (1) Do loop Until is used for the case that number of iteration is not well known. Syntax: Do Statements Loop Until ExitCondition Note that the statements within the loop is executed at least once. To avoid the unending iteration of the Do loop Until, you can add a counter to stop it and exit the Do loop Until with the Exit Do statement.

Do Loop Until (2) Function CellGrowth(InitialBiomass, GrowthRate) Dim i, Biomass, NewBiomass Biomass = InitialBiomass Do NewBiomass = Biomass * GrowthRate Biomass = Biomass + NewBiomass Loop Until Biomass > CellGrowth = Biomass End Function

Do Loop Until (3) Function CellGrowth(InitialBiomass, GrowthRate) Dim i, Biomass, NewBiomass Biomass = InitialBiomass Do Until Biomass > NewBiomass = Biomass * GrowthRate Biomass = Biomass + NewBiomass Loop CellGrowth = Biomass End Function Function CellGrowth(InitialBiomass, GrowthRate) Dim i, Biomass, NewBiomass Biomass = InitialBiomass Do NewBiomass = Biomass * GrowthRate Biomass = Biomass + NewBiomass Loop Until Biomass > CellGrowth = Biomass End Function

Loops Function CellGrowth(InitialBiomass, GrowthRate) Dim i, Biomass, NewBiomass Biomass = InitialBiomass If Biomass < Then Do NewBiomass = Biomass * GrowthRate Biomass = Biomass + NewBiomass Loop Until Biomass > End If CellGrowth = Biomass End Function

Do Loops Do While Loop Do Until Loop Do Loop Until You should pay attention to the loop structure when making a decision on which loop to use in your program.

Decision Making Statements When working with decision making statements, NEVER write your looping / ending condition as: Dim VarA As Double... If (VarA = 100) Then Always write as this: Dim VarA As Double... If (VarA >= 100) Then Why?

Array

Declare an Array Declare an array with a fixed number of elements: Syntax: Dim ArrayName(n) [ As DataType ] This array ArrayName will have n elements. Note that all elements in an array should be of the same data type. Unless you declare it as Variant type.

Operate an Array (1) Read the value in an element: For example: VarA = ArrayName(3) Put a value into an element: ArrayName(4) = 5 Note that the elements in an array are counted from 1 to n. Unless you declare an array as: Dim ArrayName(3 To 12) [ As DataType ]

Operate an Array (2) Example: Display all values in the array: Dim MyArray(10) As Integer 'Filling data into MyArray For i = 1 To 10 Worksheets("Sheet1").Cells(i, 1).Value = MyArray(i) Next i Example (Array_Example.xls)

Two-Dimensional Array Example: Dim MyArray(10, 25) As Integer 'Filling data into MyArray For i = 1 To 10 For j = 1 To 25 Worksheets("Sheet1").Cells(i, j).Value = MyArray(i, j) Next j Next i Example (Array_Example.xls)

Dynamic Array (1) If you give the array size in a declaration statement, the size of this array cannot be changed in future. If you need to declare an array that you do not know the size of before the program is executed, you can define a dynamic array. Once you know the array size during the program execution, you can re-declare the array size.

Dynamic Array (2) Example: Dim MyArray() As Integer Dim ArraySize As Integer ' Oops, now we know that we have 15 elements in MyArray(). ReDim MyArray(ArraySize)

More on Array Other programming languages (such as Java) may provide functions to check for the array size. But VB seems not to provide such a function. Therefore for the For loops to operate in arrays (please see example in previous slides), we need to provide the number of the ending condition.

Simple Data Input & Output for Excel VBA Programming

Simple Input & Output for Excel VBA (1) Input box, syntax: VarA = InputBox("Prompt", "Title", "Default Value") If user does not input any value and presses OK, it will return the default value. If user presses Cancel, it will return null. You can use a variable to capture the returned value. Example (Input_Output.xls)Example (Input_Output.xls)

Simple Input & Output for Excel VBA (2) Message Box as output, syntax: MsgBox ("This is message")

Simple Input & Output for Excel VBA (3) Message Box as output (OK button option), syntax: VarA = MsgBox("This is message", vbOKOnly, "Title") This message box will return a value of 1 if the user presses the OK button.

Simple Input & Output for Excel VBA (4) Message Box as output (OK / Cancel buttons option), syntax: VarA = MsgBox("This is message", vbOKCancel, "Title") This message box will return a value of 1 if the user presses the OK button and a value of 2 if the user presses the Cancel button.

Simple Input & Output for Excel VBA (5) Message Box as output (Yes / No buttons option), syntax: VarA = MsgBox("This is message", vbYesNo, "Title") This message box will return a value of 6 if the user presses the Yes button and a value of 7 if the user presses the No button.

Simple Input & Output for Excel VBA (6) Message Box as output (Yes / No / Cancel buttons option), syntax: VarA = MsgBox("This is message", vbYesNoCancel, "Title") This message box will return a value of 6 if the user presses the Yes button, a value of 7 if the user presses the No button and a value of 2 if the user presses the Cancel button.

Simple Input & Output for Excel VBA (7) Read data from a cell in a worksheet, syntax: VarA = Worksheets(WorksheetName).Cells(Row#, Col#).Value Put data to a cell in a worksheet, syntax: Worksheets(WorksheetName).Cells(Row#, Col#).Value = VarA

Debugging

Program Bugs There are five types of errors that can be encountered: –Syntax error – VBA editor can detect some of these for you; –Runtime error – e.g. division by zero; –Program logic error – you won’t get your expected result; –Typographical (typo) error. –Bugs from Excel or VBA (e.g. in Excel 2007, 850 x 77.1 = wse_thread/thread/7a99f3fa98f5be45/38d1b5e1be31032b?l nk=st) Example (Buggy_Program.xls)

Debugging You can insert a Break Point in the VBA editor to view how the code runs during runtime. If necessary, you can add some lines of code to trap the value of a part of the statement. To avoid a program logic error, you can write a list of what outputs are expected for defined inputs. And test your program with different input values.

Error Handling (1) You can handle potential errors in your program: –Defensive programming; –Error trapping.

Error Handling (2) Defensive Programming You can think about what are conditions that may result in runtime errors and write your code to detect and avoid those conditions. X = Val(InputBox("Enter first number ", "Input ", "")) Y = Val(InputBox("Enter second number ", "Input ", "")) If Y <> 0 Then MsgBox Str(X) & " / " & Str(Y) & " = " & Str(X / Y) Else MsgBox "Cannot divide by zero!" End If Example Program (Defensive_Programming.xls)Example Program (Defensive_Programming.xls)

Error Handling (3) Error Trapping You can use VBA commands to “trap” the error, which prevents VBA from generating the usual runtime error dialog. X = Val(InputBox("Enter first number ", "Input ", "")) Y = Val(InputBox("Enter second number ", "Input ", "")) On Error GoTo DivideByZero MsgBox Str(X) & " / " & Str(Y) & " = " & Str(X / Y) GoTo Skip1' skip over the error-handling code DivideByZero: Do Y = Val(InputBox("Enter second number ", "Input ", "")) Loop Until Y <> 0 Resume 0' Try the offending statement again Skip1: On Error GoTo 0' resume normal error-handling Example Program (Error_Trapping.xls)