CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

21
1 CS 106 Computing Fundamentals II Chapter 42 “Sub Procedures And Functions” Herbert G. Mayer, PSU CS Herbert G. Mayer, PSU CS Status 8/5/2013 Status 8/5/2013 Initial content copied verbatim from Initial content copied verbatim from CS 106 material developed by CS 106 material developed by CS professors: Cynthia Brown & Robert Martin CS professors: Cynthia Brown & Robert Martin

description

Herbert G. Mayer, PSU CS Status 8/5/2013 Initial content copied verbatim from CS 106 material developed by CS professors: Cynthia Brown & Robert Martin. CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”. Syllabus. Procedures In VBA Two Aspects of Procedures - PowerPoint PPT Presentation

Transcript of CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

Page 1: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

1

CS 106Computing Fundamentals II

Chapter 42“Sub Procedures And Functions”

Herbert G. Mayer, PSU CSHerbert G. Mayer, PSU CSStatus 8/5/2013Status 8/5/2013

Initial content copied verbatim fromInitial content copied verbatim fromCS 106 material developed byCS 106 material developed by

CS professors: Cynthia Brown & Robert MartinCS professors: Cynthia Brown & Robert Martin

Page 2: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

2

Syllabus Procedures In VBAProcedures In VBA

Two Aspects of ProceduresTwo Aspects of Procedures

Definition vs. CallDefinition vs. Call

Sub Procedure DefinitionSub Procedure Definition

Procedure NameProcedure Name

ParametersParameters

Procedure BodyProcedure Body

FunctionsFunctions

Page 3: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

3

Procedures in VBA

• Main idea: encapsulate code in its own procedureMain idea: encapsulate code in its own procedure

• Two kinds: Two kinds: Sub Sub Procedures and Procedures and FunctionsFunctions

• We’ve already seen event procedures, which are sub We’ve already seen event procedures, which are sub procedures, and we’ve seen Excel user functionsprocedures, and we’ve seen Excel user functions

• Why create more procedures?Why create more procedures? If we are repeatedly doing the same task, we can write the

code in one place, give that “place” a name, and then call the the name code –i.e. the procedure or function-- repeatedly

If a program is long and complex, we can break it into understandable parts, AKA logical modules

3

Page 4: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

4

Analogous to Problem-Solving

• Master a particular task that comes up repeatedly so Master a particular task that comes up repeatedly so you don’t have to think about how it works each time you don’t have to think about how it works each time it occursit occurs

• Break a large, complex problem into smaller, more Break a large, complex problem into smaller, more manageable partsmanageable parts

4

Page 5: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

5

Two Aspects of Procedures

• The Definition: The Definition: a separate piece of code where the a separate piece of code where the procedure is defined, as we do with event proceduresprocedure is defined, as we do with event procedures

• The Procedure Call: The Procedure Call: A piece of code that invokes a A piece of code that invokes a procedure from another place, e.g. a function, procedure from another place, e.g. a function, procedure, or event procedureprocedure, or event procedure

• Event procedures, like Event procedures, like Form_InitializeForm_Initialize or or btnProcess_ClickbtnProcess_Click, are invoked when the event , are invoked when the event happens, like happens, like loadingloading the form or the form or clickingclicking

• The explicit The explicit callcall is another method of invoking --or is another method of invoking --or activating-- the sub or functionactivating-- the sub or function

5

Page 6: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

6

Definition vs. Call

• The procedure definition is the source code that The procedure definition is the source code that specifies to the computer (compiler, interpreter) the specifies to the computer (compiler, interpreter) the name, the parameters, the return value for functions, name, the parameters, the return value for functions, and the actions to perform when calledand the actions to perform when called

• The procedure call makes the procedure actually The procedure call makes the procedure actually happenhappen

• When done, the calleé returns to the place after the When done, the calleé returns to the place after the callcall

6

Page 7: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

7

Sub Procedure Definition

A sub procedure has a name, possibly some formal A sub procedure has a name, possibly some formal parameters, and a body; always requires a pair of parameters, and a body; always requires a pair of parentheses ( ) for the formal parameter list:parentheses ( ) for the formal parameter list:

Sub Sub PrintAnswer( PrintAnswer( ByValByVal param1 As Double, param1 As Double, ByValByVal param2 param2 As Double )As Double )

Dim answer As DoubleDim answer As Double

answer = param1 + param2answer = param1 + param2

lstResults.AddItem( "param1 = " & CStr( param1 ) & lstResults.AddItem( "param1 = " & CStr( param1 ) & “param2 = ” & CStr( param2 ) )“param2 = ” & CStr( param2 ) )

lstResults.AddItem( "answer = " & CStr( answer ) )lstResults.AddItem( "answer = " & CStr( answer ) )

End SubEnd Sub

7

Page 8: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

8

Procedure Name

• Consider the header:Consider the header:

• SubSub PrintAnswer( PrintAnswer( ByVal ByVal param1 As Double,param1 As Double, ByVal ByVal param2 param2 As Double As Double ))

• PrintAnswerPrintAnswer() is the name of the procedure. A good () is the name of the procedure. A good convention is to start procedure names with capital convention is to start procedure names with capital letters, variable names with lower-case lettersletters, variable names with lower-case letters

• A good convention is to use a verb in the procedure A good convention is to use a verb in the procedure name; one that reflects what the procedure doesname; one that reflects what the procedure does

8

Page 9: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

9

ParametersSubSub PrintAnswer( PrintAnswer( ByValByVal param1 As Double, param1 As Double, ByValByVal param2 param2 As As

Double Double ))

• The formal parameters are param1 and param2The formal parameters are param1 and param2

• A A ByValByVal parameter is similar to a local variable parameter is similar to a local variable

• Assignments to the formal do NOT change the actual!Assignments to the formal do NOT change the actual!

• Its type is declared in the header -these are of type Its type is declared in the header -these are of type DoubleDouble

• A formal parameter’s initial value is set in the procedure A formal parameter’s initial value is set in the procedure call; we say the formal parameter is bound to the actual call; we say the formal parameter is bound to the actual parameter at the place of callparameter at the place of call

• Changes to Changes to ByValByVal parameters only affect the formal parameters only affect the formal parameter during the call and only inside the sub scopeparameter during the call and only inside the sub scope

9

Page 10: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

10

More on Formal ParametersSubSub PrintAnswer( PrintAnswer( ByValByVal param1 As Double, param1 As Double, ByValByVal

param2 param2 As Double As Double ))• Recall that variable names are used in two waysRecall that variable names are used in two ways

On the right side of an assignment statement, a variable name represents a value

On the left side, it represents a location where a value can be stored

• Instead of passing a value to a parameter, we could pass a Instead of passing a value to a parameter, we could pass a location, essentially hooking up the formal parameter to a location, essentially hooking up the formal parameter to a variable elsewhere in the program; this would be a reference variable elsewhere in the program; this would be a reference parameterparameter

• If you don’t specify ByVal, VBA will use pass by reference as If you don’t specify ByVal, VBA will use pass by reference as a defaulta default

• Reference parameters are used when we want the procedure Reference parameters are used when we want the procedure to change a value elsewhere in the program, e.g. the actualto change a value elsewhere in the program, e.g. the actual

10

Page 11: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

11

Procedure Body

SubSub PrintAnswer( PrintAnswer( ByValByVal param1 As Double, param1 As Double, ByValByVal param2 param2 As As Double Double ))

Dim answer As DoubleDim answer As Double

answer = param1 + answer = param1 + param2param2

lstResults.AddItem( "answer = " & CStr( answer ) )lstResults.AddItem( "answer = " & CStr( answer ) )

End SubEnd Sub

Note the local variable Note the local variable answeranswer

The result of calling this procedure is to make some text The result of calling this procedure is to make some text appear in list box lstResultsappear in list box lstResults

11

Page 12: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

12

Sub Procedure Call

• A sub procedure is called from elsewhere in the program, for A sub procedure is called from elsewhere in the program, for example from within an event procedureexample from within an event procedure

• The call uses the procedure name and arguments --AKA actual The call uses the procedure name and arguments --AKA actual parametersparameters

• A sub procedure call is a statementA sub procedure call is a statement

• Here’s what it might look like:Here’s what it might look like:

Dim Dim varA, varB varA, varB As DoubleAs Double

varA = CDbl( txtArg1.Text )varA = CDbl( txtArg1.Text )

varB = CDbl( txtArg2.Text )varB = CDbl( txtArg2.Text )

. . . And then:. . . And then:

Call Call PrintAnswer( varA, varB – 1 )PrintAnswer( varA, varB – 1 )

12

Page 13: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

13

Actual vs. Formal Parameter

• Actual parameters Actual parameters are also referred to as: are also referred to as: ArgumentsArguments

• Arguments are used to feed information to the Arguments are used to feed information to the procedureprocedure

• They are connected with the formal parameters by They are connected with the formal parameters by position; referred to as position; referred to as bindingbinding

• The actual is bound to the formal at the place of callThe actual is bound to the formal at the place of call

13

Page 14: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

14

Examples

With this procedure code:With this procedure code:

SubSub PrintAnswer( PrintAnswer( ByValByVal param1 param1 As DoubleAs Double, , ByValByVal param2 param2 As As Double Double ))

DimDim answer answer As Double As Double

answer = param1 + param2answer = param1 + param2

lstResults.AddItem( "answer = " & CStr( answer ) )lstResults.AddItem( "answer = " & CStr( answer ) )

End SubEnd Sub

The procedure call:The procedure call:

CallCall PrintAnswer( 3, 5 ) PrintAnswer( 3, 5 ) sets param1 = 3 and param2 = 5sets param1 = 3 and param2 = 5

CallCall PrintAnswer( x, y ) PrintAnswer( x, y ) sets param1 = x and param2 = y, whatever sets param1 = x and param2 = y, whatever the values of x and y happen to bethe values of x and y happen to be

14

Page 15: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

15

Functions

• Functions have one extra element: they return a valueFunctions have one extra element: they return a value

• We’ve seen examples of functions built into VBA: for We’ve seen examples of functions built into VBA: for example, Format, or any user functionexample, Format, or any user function

• A function can have parametersA function can have parameters

• A function returns a result that has a particular data A function returns a result that has a particular data typetype

• A function call is an expression with a data typeA function call is an expression with a data type

15

Page 16: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

16

Function Definition

• A function procedure definition has a name, possible A function procedure definition has a name, possible formal parameters, a body of code, and a typeformal parameters, a body of code, and a type

• Example function definition:Example function definition:

FunctionFunction ComputeAnswer( ComputeAnswer(

ByValByVal param1 param1 As DoubleAs Double,,

ByValByVal param2 param2 As DoubleAs Double) ) As DoubleAs Double

ComputeAnswer = param1 + param2ComputeAnswer = param1 + param2

End Function End Function

16

Page 17: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

17

About the Function Definition

• To set the value returned by the function, we use an To set the value returned by the function, we use an assignment to the name of the function:assignment to the name of the function:

• Specifying the type of the function at the end of the Specifying the type of the function at the end of the header appears to be optional, even with Option header appears to be optional, even with Option Explicit turned on, but it is a good idea to do itExplicit turned on, but it is a good idea to do it

• Note the function just computes a value and returns Note the function just computes a value and returns at the end of the function body at the end of the function body

17

Page 18: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

18

Function Call

• A function is called from elsewhere in the program, A function is called from elsewhere in the program, for example from within some event procedurefor example from within some event procedure

• The call uses the function name and arguments (AKA The call uses the function name and arguments (AKA actual parameters), and returns a valueactual parameters), and returns a value

• Here’s what it might look like:Here’s what it might look like:

varA = CDbl( txtArg1.Text )varA = CDbl( txtArg1.Text )

varB = CDbl( txtArg2.Text )varB = CDbl( txtArg2.Text )

answer = ComputeAnswer( varA, varB )answer = ComputeAnswer( varA, varB )

18

Page 19: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

19

What Happens in Procedure Call

• The expressions for the argument values are The expressions for the argument values are evaluated, and the formal parameters are set to those evaluated, and the formal parameters are set to those valuesvalues

• The Dim statements for the procedure are used to The Dim statements for the procedure are used to create any local variablescreate any local variables

• The code for the procedure is executedThe code for the procedure is executed

• Control returns to the line after the procedure call Control returns to the line after the procedure call (sub procedure), or to the line of the call with the (sub procedure), or to the line of the call with the returned value (function)returned value (function)

19

Page 20: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

20

Control Flow for Procedure Call

Some program code

Procedure call

More program code

Procedure code

Set parameter values

Return value (function)

Page 21: CS 106 Computing Fundamentals II Chapter 42 “ Sub Procedures And Functions ”

21

Procedures and Program Structure

• The main program in the procedure demo is the event The main program in the procedure demo is the event procedure for btnResultsprocedure for btnResults

• We could have simply put all the code in this We could have simply put all the code in this procedureprocedure

• To make our program better structured and more To make our program better structured and more readable, though, break major step into their own readable, though, break major step into their own procedures or functionsprocedures or functions

21