Presentation is loading. Please wait.

Presentation is loading. Please wait.

Control Statements Making Decision in Your Program.

Similar presentations


Presentation on theme: "Control Statements Making Decision in Your Program."— Presentation transcript:

1 Control Statements Making Decision in Your Program

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

3 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

4 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

5 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

6 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 ]

7 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

8 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

9 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 ]

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

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

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

13 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

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

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

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

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

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

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

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

21 Do Loop Until (3) Function CellGrowth(InitialBiomass, GrowthRate) Dim i, Biomass, NewBiomass Biomass = InitialBiomass Do Until Biomass > 10000 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 > 10000 CellGrowth = Biomass End Function

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

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

24 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?

25 Array

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

27 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 ]

28 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)

29 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)

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

31 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)

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

33 Simple Data Input & Output for Excel VBA Programming

34 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)

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

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

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

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

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

40 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

41 Debugging

42 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 = 100000 http://groups.google.com/group/microsoft.public.excel/bro wse_thread/thread/7a99f3fa98f5be45/38d1b5e1be31032b?l nk=st) Example (Buggy_Program.xls)

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

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

45 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)

46 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)


Download ppt "Control Statements Making Decision in Your Program."

Similar presentations


Ads by Google