Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own...

28
Sub Procedures and Functions

Transcript of Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own...

Page 1: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

Sub Procedures and Functions

Page 2: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

2

Procedures in VBA

• The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

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

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

code in one place and then call the procedure repeatedly; the call is much simpler than the entire code

– If a program is long and complex, we can break it into understandable parts

Page 3: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

3

Parallel with Problem-Solving Strategies

• Master 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 parts

Page 4: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

4

Example: Left Turn

• When you first learn to drive, you learn a whole procedure for left turn:– [Check it is ok to get in the left lane]– [Signal a lane change]– [Get in the left lane]– Signal for a left– Slow down at the intersection– Look for oncoming traffic or pedestrians; stop if

necessary– Turn when the way is clear, at a safe speed

Page 5: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

5

Left turn…

• After you know how to drive, you use this procedure without needing to think through all the steps explicitly

• If someone says “Turn left” you do all the steps; you don’t need them spelled out

• You can turn left at any corner, not just the ones where you learned to drive

• You have internalized a left-turn procedure

Page 6: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

6

Two Aspects of Procedures

• The 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 within an event procedure or other procedure

• Event procedures, like Form_Initialize or btnProcess_Click in our RealEstate V2 example, are invoked when the event happens, like loading the form or clicking the button, instead of using an explicit call in the code

Page 7: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

7

Definition vs Call

• The definition is like the place in your brain where you remember how to do the left turn. The definition is established when you learn how to turn left.

• The call is like having someone tell you, “Turn left at the next corner,” after you know how to drive. It happens in a completely different context than learning to drive, but it makes you go back to what you learned and execute the procedure

Page 8: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

8

Definition vs Call

• So the procedure definition is the code that tells the computer how to do the procedure

• The procedure call makes the procedure actually happen

• (The examples we use next are in workbook SubAndFunctionDemo)

Page 9: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

9

Sub Procedure Definition

• A sub procedure has a name, possible parameters, and a body of code.

• Example sub procedure definition:

Sub PrintAnswer(ByVal param1 As Double, ByVal param2 As Double) Dim answer As Double answer = param1 + param2 lstResults.AddItem ("param1 = " & CStr(param1) & (" param2 = ") & CStr(param2)) lstResults.AddItem ("answer = " & CStr(answer))End Sub

• Let’s look at the elements more closely…

Page 10: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

10

Procedure Name

• Consider the parts of the header:Sub PrintAnswer(ByVal param1 As Double, ByVal param2 As

Double)

• PrintAnswer is the name of the procedure. We’ll start procedure names with capital letters (and variable names with lower-case letters).

• Use a verb in the procedure name; one that reflects what the procedure does.

Page 11: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

11

ParametersSub PrintAnswer(ByVal param1 As Double, ByVal param2 As Double)

• The (formal) parameters are param1 and param2• A ByVal parameter is very similar to a local variable• Its type is declared in the header (these are type Double)• Its initial value is set in the procedure call (NOT in the

definition!)• Changes to ByVal parameters have no effect on variables

elsewhere in the program; still, it is best as a programming practice not to set them to new values inside the procedure

Page 12: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

12

More on Formal ParametersSub PrintAnswer(ByVal param1 As Double, ByVal param2 As Double)

• Recall 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 parameter. If 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

• Our preference is to use value parameters except in very unusual situations

Page 13: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

13

Procedure Body

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

Dim answer As Double

answer = param1 + param2lstResults.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

Page 14: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

14

Sub Procedure Call

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

• The call uses the procedure name and arguments (sometimes called actual parameters)

• A sub procedure call is a statement• Here’s what it might look like:

Dim varA, varB As Double varA = CDbl(txtArg1.Text) varB = CDbl(txtArg2.Text) Call PrintAnswer(varA, varB - 1)

Page 15: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

15

Arguments vs Formal Parameters

• Arguments are used to feed information to the procedure• They are connected with the formal parameters by position; the

names are irrelevant• Think of the procedure as a sealed room with a slot for each

parameter• The call puts a value through each slot• Inside the room, there is a name on each slot (the name of the

formal parameter). Whatever value comes through the slot, that name is used for it throughout the procedure execution.

• The people inside the room never know what the values are called on the outside

Page 16: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

16

Examples

• With this procedure code:Sub PrintAnswer(ByVal param1 As Double, ByVal param2 As Double) Dim answer As Double answer = param1 + param2 lstResults.AddItem ("answer = " & CStr(answer))End Sub

• The procedure call Call PrintAnswer(3, 5) sets param1 = 3 and param2 = 5Call PrintAnswer(x,y) sets param1 = x and param2 = y,

whatever the values of x and y happen to be

Page 17: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

17

Function Procedures

• Function procedures have one extra element: they return a value

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

• A function can have parameters• A function returns a result that has a particular

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

Page 18: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

18

Function Definition

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

• Example function definition:

Function ComputeAnswer(ByVal param1 As Double, ByVal param2 As Double) As Double

ComputeAnswer = param1 + param2End Function

Page 19: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

19

About the Function Definition

• 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 it

• Note the function just computes a value and returns (at the end of the code).

ComputeAnswer = param1 + param2

Page 20: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

20

Function Call

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

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

• Here’s what it might look like: varA = CDbl(txtArg1.Text) varB = CDbl(txtArg2.Text) answer = ComputeAnswer(varA, varB)

Page 21: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

21

What Happens in a Procedure Call

• The 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 variables

• The 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)

Page 22: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

22

A Picture of the Control Flowfor a Procedure Call

Some program code

Procedure call

More program code

Procedure code

Set parameter values

Return value (function)

Page 23: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

Let’s look the procedure demo

Page 24: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

24

Procedures and Program Structure

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

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

• To make our program better structured and more readable, though, we broke out each major step into its own procedure or function

Page 25: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

25

The Main Procedure Private Sub btnResults_Click() Dim bmi, thr As Integer

'compute bmi bmi = ComputeBMI()

'compute thr thr = ComputeTHR()

'print results with warning if too fat or thin Call PrintResults(bmi, thr)

End Sub

Page 26: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

26

Pseudocode

• One way to design a program is to use flowcharts

• Another way is to write pseudocode (“pseudo”, as a prefix, means “false”; it’s pronounced like sudo)

• With pseudocode, you write down the main steps of the program and as much detail as you want, but informally, instead of as code

• Then, you gradually fill in with real code

Page 27: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

27

Example

• In the prior demo there were three main steps• I wrote the three steps as pseudocode and

inserted them as comments in the event procedure shell for btnResults_Click

• Then I filled in the code, step by step. I wrote the printing code as I went along to facilitate debugging.

Page 28: Sub Procedures and Functions. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions)

28

Choices

• You can use either pseudocode or flowcharts when designing a program (or any other process, for that matter)

• If you use pseudocode for complex if statements, you should set up the structure of the if statement with indenting, else’s, etc

• You can always mix and match: for example, write pseudocode but do flowcharts for complex if statements

• Always do some planning; at the very least, write down your main steps as comments before you start coding