+ All Categories
Home > Documents > Control Statements Making Decision in Your Program.

Control Statements Making Decision in Your Program.

Date post: 20-Dec-2015
Category:
View: 213 times
Download: 0 times
Share this document with a friend
46
Control Statements Making Decision in Your Program
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 ThenStatements

[ ElseIf Condition2 ThenStatements ]

[ ElseStatements ]

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 IfEnd Function

If True ?

StatementsWhen Yes

Yes

No

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 IfEnd Function

If True ?

StatementsWhen Yes

YesNo

StatementsWhen No

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 IfEnd Function

If True ?

StatementsWhen Yes

YesNo

ElseIfTrue?

YesNo

StatementsWhen Yes

StatementsWhen No

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 = BiomassEnd Function

If i <= 10

Statements

Yes

No

i = i + 1

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 ]StatementsIf (ExitCondition) Then

Exit ForEnd 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 <= 10000 NewBiomass = Biomass * GrowthRate Biomass = Biomass + NewBiomass Loop CellGrowth = BiomassEnd Function

Start

StatementsIn the Loop

Loop?

End

NoYes

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

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 < 10000 NewBiomass = Biomass * GrowthRate Biomass = Biomass + NewBiomass i = i + 1 If (i > 100) Then Exit Do End If Loop CellGrowth = BiomassEnd 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 ExitConditionStatements

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 > 10000 NewBiomass = Biomass * GrowthRate Biomass = Biomass + NewBiomass Loop CellGrowth = BiomassEnd Function

Start

StatementsIn the Loop

Exit?

End

No

Yes

Do Until Loop (3)

Function CellGrowth(InitialBiomass, GrowthRate)

Dim i, Biomass, NewBiomass Do While Biomass <= 10000 NewBiomass = Biomass *

GrowthRate Biomass = Biomass +

NewBiomass Loop CellGrowth = BiomassEnd Function

Function CellGrowth(InitialBiomass, GrowthRate)

Dim i, Biomass, NewBiomass Biomass = InitialBiomass Do Until Biomass > 10000 NewBiomass = Biomass *

GrowthRate Biomass = Biomass +

NewBiomass Loop CellGrowth = BiomassEnd Function

Do Loop Until (1)

• Do loop Until is used for the case that number of iteration is not well known.

• Syntax:DoStatements

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 > 10000 CellGrowth = BiomassEnd Function

Start

StatementsIn the Loop

Exit?

End

No

Yes

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 = BiomassEnd Function

Function CellGrowth(InitialBiomass, GrowthRate)

Dim i, Biomass, NewBiomass Biomass = InitialBiomass Do NewBiomass = Biomass *

GrowthRate Biomass = Biomass +

NewBiomass Loop Until Biomass > 10000 CellGrowth = BiomassEnd Function

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 = BiomassEnd Function

Do LoopsStart

StatementsIn the Loop

Loop?

End

NoYes

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.

Start

StatementsIn the Loop

Exit?

End

No

Yes

Start

StatementsIn the Loop

Exit?

End

No

Yes

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 10Worksheets("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 10For j = 1 To 25

Worksheets("Sheet1").Cells(i, j).Value = MyArray(i, j)

Next jNext 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)

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 =

100000 http://groups.google.com/group/microsoft.public.excel/browse_thread/thread/7a99f3fa98f5be45/38d1b5e1be31032b?lnk=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)

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 DivideByZeroMsgBox 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 <> 0Resume 0 ' Try the offending statement again

Skip1:On Error GoTo 0 ' resume normal error-handling

• Example Program (Error_Trapping.xls)


Recommended