Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 CS 106 Computing Fundamentals II Chapter 42 “Sub Procedures And Functions” Herbert G. Mayer, PSU CS Status 8/5/2013 Initial content copied verbatim from.

Similar presentations


Presentation on theme: "1 CS 106 Computing Fundamentals II Chapter 42 “Sub Procedures And Functions” Herbert G. Mayer, PSU CS Status 8/5/2013 Initial content copied verbatim from."— Presentation transcript:

1 1 CS 106 Computing Fundamentals II Chapter 42 “Sub Procedures And Functions” 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

2 2 Syllabus Procedures In VBA Procedures In VBA Two Aspects of Procedures Two Aspects of Procedures Definition vs. Call Definition vs. Call Sub Procedure Definition Sub Procedure Definition Procedure Name Procedure Name Parameters Parameters Procedure Body Procedure Body Functions Functions

3 3 Procedures in VBA Main idea: encapsulate code in its own procedureMain idea: encapsulate code in its own procedure Two kinds: Sub Procedures and FunctionsTwo kinds: Sub Procedures and Functions We’ve already seen event procedures, which are sub procedures, and we’ve seen Excel user functionsWe’ve already seen event procedures, which are sub procedures, 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

4 4 Analogous to Problem-Solving Master a particular task that comes up repeatedly so you don’t have to think about how it works each time it occursMaster a particular task that comes up repeatedly so you don’t have to think about how it works each time it occurs Break a large, complex problem into smaller, more manageable partsBreak a large, complex problem into smaller, more manageable parts 4

5 5 Two Aspects of Procedures The Definition: a separate piece of code where the procedure is defined, as we do with event proceduresThe Definition: a separate piece of code where the procedure is defined, as we do with event procedures The Procedure Call: A piece of code that invokes a procedure from another place, e.g. a function, procedure, or event procedureThe Procedure Call: A piece of code that invokes a procedure from another place, e.g. a function, procedure, or event procedure Event procedures, like Form_Initialize or btnProcess_Click, are invoked when the event happens, like loading the form or clickingEvent procedures, like Form_Initialize or btnProcess_Click, are invoked when the event happens, like loading the form or clicking The explicit call is another method of invoking --or activating-- the sub or functionThe explicit call is another method of invoking --or activating-- the sub or function 5

6 6 Definition vs. Call The procedure definition is the source code that specifies to the computer (compiler, interpreter) the name, the parameters, the return value for functions, and the actions to perform when calledThe procedure definition is the source code that specifies to the computer (compiler, interpreter) the name, the parameters, the return value for functions, and the actions to perform when called The procedure call makes the procedure actually happenThe procedure call makes the procedure actually happen When done, the calleé returns to the place after the callWhen done, the calleé returns to the place after the call 6

7 7 Sub Procedure Definition A sub procedure has a name, possibly some formal parameters, and a body; always requires a pair of parentheses ( ) for the formal parameter list: Sub PrintAnswer( ByVal param1 As Double, ByVal param2 As Double ) Dim answer As Double Dim answer As Double answer = param1 + param2 answer = param1 + param2 lstResults.AddItem( "param1 = " & CStr( param1 ) & “param2 = ” & CStr( param2 ) ) lstResults.AddItem( "param1 = " & CStr( param1 ) & “param2 = ” & CStr( param2 ) ) lstResults.AddItem( "answer = " & CStr( answer ) ) lstResults.AddItem( "answer = " & CStr( answer ) ) End Sub 7

8 8 Procedure Name Consider the header:Consider the header: Sub PrintAnswer( ByVal param1 As Double, ByVal param2 As Double )Sub PrintAnswer( ByVal param1 As Double, ByVal param2 As Double ) PrintAnswer() is the name of the procedure. A good convention is to start procedure names with capital letters, variable names with lower-case lettersPrintAnswer() is the name of the procedure. A good convention is to start procedure names with capital letters, variable names with lower-case letters A good convention is to use a verb in the procedure name; one that reflects what the procedure doesA good convention is to use a verb in the procedure name; one that reflects what the procedure does 8

9 9 Parameters Sub PrintAnswer( ByVal param1 As Double, ByVal param2 As Double ) The formal parameters are param1 and param2The formal parameters are param1 and param2 A ByVal parameter is similar to a local variableA ByVal 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 DoubleIts type is declared in the header -these are of type Double A formal parameter’s initial value is set in the procedure call; we say the formal parameter is bound to the actual parameter at the place of callA formal parameter’s initial value is set in the procedure call; we say the formal parameter is bound to the actual parameter at the place of call Changes to ByVal parameters only affect the formal parameter during the call and only inside the sub scopeChanges to ByVal parameters only affect the formal parameter during the call and only inside the sub scope 9

10 10 More on Formal Parameters Sub PrintAnswer( ByVal param1 As Double, ByVal param2 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 location, essentially hooking up the formal parameter to a variable elsewhere in the program; this would be a reference parameterInstead of passing a value to a parameter, we could pass a location, essentially hooking up the formal parameter to a variable elsewhere in the program; this would be a reference parameter If you don’t specify ByVal, VBA will use pass by reference as a defaultIf you don’t specify ByVal, VBA will use pass by reference as a default Reference parameters are used when we want the procedure to change a value elsewhere in the program, e.g. the actualReference parameters are used when we want the procedure to change a value elsewhere in the program, e.g. the actual 10

11 11 Procedure Body Sub PrintAnswer( ByVal param1 As Double, ByVal param2 As Double ) Dim answer As Double Dim answer As Double answer = param1 + param2 answer = param1 + param2 lstResults.AddItem( "answer = " & CStr( answer ) ) End Sub Note the local variable answer The result of calling this procedure is to make some text appear in list box lstResults 11

12 12 Sub Procedure Call A sub procedure is called from elsewhere in the program, for example from within an event procedureA sub procedure is called from elsewhere in the program, for example from within an event procedure The call uses the procedure name and arguments --AKA actual parametersThe call uses the procedure name and arguments --AKA actual parameters 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 varA, varB As Double Dim varA, varB As Double varA = CDbl( txtArg1.Text ) varA = CDbl( txtArg1.Text ) varB = CDbl( txtArg2.Text ) varB = CDbl( txtArg2.Text )... And then:... And then: Call PrintAnswer( varA, varB – 1 ) Call PrintAnswer( varA, varB – 1 ) 12

13 13 Actual vs. Formal Parameter Actual parameters are also referred to as: ArgumentsActual parameters are also referred to as: Arguments Arguments are used to feed information to the procedureArguments are used to feed information to the procedure They are connected with the formal parameters by position; referred to as bindingThey are connected with the formal parameters by position; referred to as binding The actual is bound to the formal at the place of callThe actual is bound to the formal at the place of call 13

14 14 Examples With this procedure code: Sub PrintAnswer( ByVal param1 As Double, ByVal param2 As Double ) Dim answer As Double Dim answer As Double answer = param1 + param2 answer = param1 + param2 lstResults.AddItem( "answer = " & CStr( answer ) ) lstResults.AddItem( "answer = " & CStr( answer ) ) End Sub The procedure call: Call PrintAnswer( 3, 5 ) sets param1 = 3 and param2 = 5 Call PrintAnswer( x, y ) sets param1 = x and param2 = y, whatever the values of x and y happen to be 14

15 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 example, Format, or any user functionWe’ve seen examples of functions built into VBA: for example, Format, or any user function A function can have parametersA function can have parameters A function returns a result that has a particular data typeA function returns a result that has a particular data type A function call is an expression with a data typeA function call is an expression with a data type 15

16 16 Function Definition A function procedure definition has a name, possible formal parameters, a body of code, and a typeA function procedure definition has a name, possible formal parameters, a body of code, and a type Example function definition:Example function definition: Function ComputeAnswer( ByVal param1 As Double, ByVal param2 As Double) As Double ComputeAnswer = param1 + param2 ComputeAnswer = param1 + param2 End Function 16

17 17 About the Function Definition To set the value returned by the function, we use an assignment to the name of the function:To set the value returned by the function, we use an assignment to the name of the function: Specifying the type of the function at the end of the header appears to be optional, even with Option Explicit turned on, but it is a good idea to do itSpecifying the type of the function at the end of the header appears to be optional, even with Option Explicit turned on, but it is a good idea to do it Note the function just computes a value and returns at the end of the function bodyNote the function just computes a value and returns at the end of the function body 17

18 18 Function Call A function is called from elsewhere in the program, for example from within some event procedureA function is called from elsewhere in the program, for example from within some event procedure The call uses the function name and arguments (AKA actual parameters), and returns a valueThe call uses the function name and arguments (AKA actual 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

19 19 What Happens in Procedure Call The expressions for the argument values are evaluated, and the formal parameters are set to those valuesThe expressions for the argument values are evaluated, and the formal parameters are set to those values The Dim statements for the procedure are used to create any local variablesThe Dim statements for the procedure are used to create 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 (sub procedure), or to the line of the call with the returned value (function)Control returns to the line after the procedure call (sub procedure), or to the line of the call with the returned value (function) 19

20 20 Control Flow for Procedure Call Some program code Procedure call More program code Procedure code Set parameter values Return value (function)

21 21 Procedures and Program Structure The main program in the procedure demo is the event procedure for btnResultsThe main program in the procedure demo is the event procedure for btnResults We could have simply put all the code in this procedureWe could have simply put all the code in this procedure To make our program better structured and more readable, though, break major step into their own procedures or functionsTo make our program better structured and more readable, though, break major step into their own procedures or functions 21


Download ppt "1 CS 106 Computing Fundamentals II Chapter 42 “Sub Procedures And Functions” Herbert G. Mayer, PSU CS Status 8/5/2013 Initial content copied verbatim from."

Similar presentations


Ads by Google