Download ppt - Sub Programs

Transcript
Page 1: Sub Programs

Sub Programs

To Solve a Problem, First To Solve a Problem, First Make It SimplerMake It Simpler

Page 2: Sub Programs

Top Down Design

Top Down Design Top Down Design Start with overall goal.Start with overall goal.Break Goal into Sub GoalsBreak Goal into Sub GoalsBreak Sub Goals into Sub Sub GoalsBreak Sub Goals into Sub Sub GoalsUntil the Sub-Sub-Sub-Sub Goals Until the Sub-Sub-Sub-Sub Goals

are Easy. are Easy.

Page 3: Sub Programs

Functions

The VB Function is derived from a The VB Function is derived from a mathematical function:mathematical function: f(x) = x2 + 3x + 1f(x) = x2 + 3x + 1

We use the function to calculate a We use the function to calculate a single value.single value.

Page 4: Sub Programs

Example Function

A function called “factorial” takes in a A function called “factorial” takes in a number and returns its factorial.number and returns its factorial.fact(5) returns 120fact(5) returns 120

Factorial Function

Number

Factorial

Page 5: Sub Programs

How Functions are Used

Functions are defined somewhere.Functions are defined somewhere.They are then used in another They are then used in another

place.place.The place they are used is called The place they are used is called

the Calling Function or Calling the Calling Function or Calling Sub Procedure or Calling RoutineSub Procedure or Calling Routine

Page 6: Sub Programs

Defining Our Own Functions

Functions have several parts to Functions have several parts to them:them:The HeaderThe HeaderThe BodyThe BodyThe End StatementThe End Statement

Page 7: Sub Programs

Function Structure

Header

Body

End

Function even (num as integer) as IntegerIf((num mod 2) = 0) Then

even = trueReturn

End Ifeven = false

End Function

Page 8: Sub Programs

The Function Header

The function header has:The function header has: the word Function, the word Function, the name of the function, the name of the function, the list of arguments it will acceptsthe list of arguments it will acceptsthe function typethe function type

Function Norb (fleeb as Integer) as IntegerFunction Norb (fleeb as Integer) as Integer

Page 9: Sub Programs

Function Headers Must Have

The Word The Word FunctionFunction at their beginning at their beginningA A NameName - The names are restricted. - The names are restricted.An An Argument ListArgument List (possibly empty) (possibly empty)

What values will be sent in? What values will be sent in? A A TypeType

The function is going to return a value, what type The function is going to return a value, what type will it be?will it be?

Page 10: Sub Programs

Function Bodies

A series of statements.A series of statements.There is one statement that must be in There is one statement that must be in

that series,that series,function_name = expressionfunction_name = expressionThis indicates what value should be This indicates what value should be

returned from the function.returned from the function.

Page 11: Sub Programs

Early Out

The function body can contain an The function body can contain an Exit FunctionExit Function statement. statement.This returns control immediately to This returns control immediately to

the calling function.the calling function.Useful for Finding Something and Useful for Finding Something and

QuittingQuitting

Page 12: Sub Programs

Function End Statement

This contains the words End This contains the words End Function on a line by itself:Function on a line by itself:

End FunctionEnd FunctionThis is used to indicate the last This is used to indicate the last

statement in the Function statement in the Function Definition.Definition.

Page 13: Sub Programs

Example Function

Two Numbers In, Smaller One OutTwo Numbers In, Smaller One OutFunction Smaller (A as Integer, B as Integer) Function Smaller (A as Integer, B as Integer)

As IntegerAs Integer If A < B ThenIf A < B Then Smaller = ASmaller = A ElseElse Smaller = BSmaller = B End IfEnd IfEnd FunctionEnd Function

Page 14: Sub Programs

How do we get numbers in?

What if we want to send a value in?What if we want to send a value in?We use an argument to receive values into the We use an argument to receive values into the

function.function.The arguments are used like variables and have The arguments are used like variables and have

what ever value was sent to them by the calling what ever value was sent to them by the calling program.program.

Arguments are described in the Header of the Arguments are described in the Header of the function.function.

Page 15: Sub Programs

Argument List of a Function

The argument list will have the The argument list will have the following form:following form:

( ByVal var_name as type , ByVal ( ByVal var_name as type , ByVal next_var as type)next_var as type)

Parts in italics are user defined, those Parts in italics are user defined, those in bold are optional, everything else is in bold are optional, everything else is required.required.

Page 16: Sub Programs

Argument List

Allows the function to operate on Allows the function to operate on differing data.differing data.

Variables followed by type (as in Variables followed by type (as in Dim)Dim)

In Excel these are likely to be In Excel these are likely to be ranges.ranges.

Page 17: Sub Programs

Argument List

The number of arguments are up to you.The number of arguments are up to you.Each argument must have a typeEach argument must have a typeEach argument can be plain or ByValEach argument can be plain or ByValArguments are named just like variablesArguments are named just like variables( Fleeb As Integer)( Fleeb As Integer)

Page 18: Sub Programs

Using the Argument List

Values are transferred to the arguments Values are transferred to the arguments in order. in order. The first value in the calling routine The first value in the calling routine

become the value of the first argumentbecome the value of the first argumentThe second value becomes the second The second value becomes the second

argument and so on.argument and so on.

Page 19: Sub Programs

x = 2x = 2For i = 1 to 10For i = 1 to 10 y = pow(i,x)y = pow(i,x)next inext iMsgBox CStr(y)MsgBox CStr(y)

Function Pow (m as integer, ex as single) as SingleFunction Pow (m as integer, ex as single) as Single Pow = m ^ exPow = m ^ exEnd FunctionEnd Function

Connecting the Function

Page 20: Sub Programs

Argument Examples

Function Fleeb (R1 As Range) As IntegerFunction Fleeb (R1 As Range) As IntegerTakes in a range, returns an integer.Takes in a range, returns an integer.

Function Norb(R1 As Range, num As Function Norb(R1 As Range, num As Integer) As SingleInteger) As SingleTakes in a range and an integer, returns a Takes in a range and an integer, returns a

single.single.

Page 21: Sub Programs

ByVal Modifier

The optional ByVal modifier means that doing The optional ByVal modifier means that doing things to the argument in the function will things to the argument in the function will have no effect on them in the calling function.have no effect on them in the calling function.

This is good if we have several people writing This is good if we have several people writing a program and we want to make sure our a program and we want to make sure our function doesn’t interfere with what they are function doesn’t interfere with what they are doing.doing.

Page 22: Sub Programs

Argument Communication

Plain arguments are two way Plain arguments are two way communication.communication.

ByVal arguments are one way ByVal arguments are one way communications between the communications between the calling function and the function.calling function and the function.

Page 23: Sub Programs

How ByVal Effects the Connection

Before ByValBefore ByVal

After ByValAfter ByVal

Page 24: Sub Programs

Side Effects

Functions are not supposed to have any Functions are not supposed to have any effect other than returning a value.effect other than returning a value.

If they do anything else it is known as a side If they do anything else it is known as a side effect.effect.

Side effects are usually not a good idea.Side effects are usually not a good idea.Someone using your function has to be very, Someone using your function has to be very,

very careful so that your function doesn’t mess very careful so that your function doesn’t mess up their program.up their program.

Page 25: Sub Programs

Sub Procedures

Sometimes we want to do something more Sometimes we want to do something more than just pass back a single value.than just pass back a single value.

We can use a Sub Procedure to modify the We can use a Sub Procedure to modify the value of several arguments.value of several arguments.

This is not a side effect with a Sub This is not a side effect with a Sub Procedure, it is what they are designed for.Procedure, it is what they are designed for.

Page 26: Sub Programs

Defining Sub Procedures

Sub Procedures also have a header, body, and Sub Procedures also have a header, body, and an end statementan end statement

The header looks like this:The header looks like this:SUBSUB sub_name sub_name (( ByValByVal var_name var_name asas typetype , ... , ...))It doesn’t have a return type because it doesn’t It doesn’t have a return type because it doesn’t

“return” a value.“return” a value.Values are passed back through the argument Values are passed back through the argument

list.list.

Page 27: Sub Programs

Calling Sub Procedures

Unlike Functions, Sub Procedures are Unlike Functions, Sub Procedures are called using a special command.called using a special command.

CallCall is used in front of the Sub: is used in front of the Sub:Call Sort_Array(Arg1,Arg2)Call Sort_Array(Arg1,Arg2)This is done because the Sub is not evaluated This is done because the Sub is not evaluated

to some value - it returns its value through the to some value - it returns its value through the parameters in its argument list.parameters in its argument list.

Page 28: Sub Programs

Sub Procedure Body

The body of a Sub Procedure can have a The body of a Sub Procedure can have a series of statementsseries of statements

There is no need to set the name of the Sub There is no need to set the name of the Sub to a value, after all, we’re returning values to a value, after all, we’re returning values via the argument list.via the argument list.

A Exit Sub statement can be used to return A Exit Sub statement can be used to return control to the calling subprogram.control to the calling subprogram.

Page 29: Sub Programs

Sub Procedure End Statement

The Sub Procedure is terminated The Sub Procedure is terminated by the statement End Sub.by the statement End Sub.

Page 30: Sub Programs

Scoping

Variables are only visible in a certain Variables are only visible in a certain area - this area is known as their scope.area - this area is known as their scope.

The ability to encapsulate functionality The ability to encapsulate functionality in sub programs is enhanced by the in sub programs is enhanced by the limited scope of the variables in the sub-limited scope of the variables in the sub-programs.programs.

Page 31: Sub Programs

Scoping, Con’t

Places where a variable can’t be Places where a variable can’t be seen, it can’t be modified. So we seen, it can’t be modified. So we don’t have to worry about it. (Out don’t have to worry about it. (Out of sight, out of mind...)of sight, out of mind...)

Page 32: Sub Programs

Scoping With Function/Sub

Variables declared within a Sub or Variables declared within a Sub or Function are only visible within Function are only visible within them.them.

Sub Fleeb ()Sub Fleeb ()Dim a,bDim a,ba = 0a = 0

End SubEnd Sub

Sub Norb ()Sub Norb ()Dim a,bDim a,ba = 3a = 3

End SubEnd Sub

Page 33: Sub Programs

Scoping Within a Module

Variables declared at the module level Variables declared at the module level are visible anywhere in the module.are visible anywhere in the module. Module level variables are specified at Module level variables are specified at

the top of the page.the top of the page.Except where they are blocked by a Except where they are blocked by a

local variable of the same name.local variable of the same name.

Page 34: Sub Programs

Illustration of Scoping

Sub Fleeb ()Sub Fleeb ()Dim aDim aa = 0a = 0‘‘a,b,c,d are visiblea,b,c,d are visibleEnd SubEnd Sub

Sub Norb ()Sub Norb ()Dim bDim bb = 3b = 3‘‘b (the local one), b (the local one), c, d ‘are visiblec, d ‘are visibleEnd SubEnd Sub

Module’s General DeclarationModule’s General DeclarationDim b,c,dDim b,c,d

Page 35: Sub Programs

Modules in VB

Modules (files containing just code) Modules (files containing just code) allow us to pass code between allow us to pass code between spreadsheets.spreadsheets.

Sometimes you want to give out your Sometimes you want to give out your code in such a way that it can be added code in such a way that it can be added to an existing spreadsheet.to an existing spreadsheet.

Page 36: Sub Programs

Global Variables

Modules in a Spreadsheet can have Modules in a Spreadsheet can have variables accessible in two modules.variables accessible in two modules.

This is done by declaring it This is done by declaring it “Global”, in which case it can be “Global”, in which case it can be accessed from anywhere in the accessed from anywhere in the spreadsheet’s VBA code.spreadsheet’s VBA code.

Page 37: Sub Programs

Scoping in a Project

Module1Module1Global A,BGlobal A,BDim C,DDim C,D

Form1Form1Dim B,GDim B,G

Form2Form2Dim B,G,KDim B,G,K

Sub CSub CDim C,HDim C,H

Sub E ()Sub E ()Dim B,A,LDim B,A,L

Function DFunction DDim B,JDim B,J Function FFunction F

Dim L,M,J,EDim L,M,J,E

Sub ASub ADim A,EDim A,E

Function BFunction BDim B,FDim B,F

Page 38: Sub Programs

Variable Lifetime

Variables only last as long as the code block Variables only last as long as the code block they are in. they are in.

After the code ends they evaporate.After the code ends they evaporate.Unless:Unless:

The values can be preserved by passing them The values can be preserved by passing them back.back.

The variables and their values can be preserved The variables and their values can be preserved by declaring them static.by declaring them static.

Page 39: Sub Programs

Summary

Over the last few weeks we have seen how VB Over the last few weeks we have seen how VB supports the decomposition of functionality.supports the decomposition of functionality.

This included:This included:the ability to declare a Sub or Functionthe ability to declare a Sub or Functionthe ability to pass values from one Sub/Function the ability to pass values from one Sub/Function

to another,to another,the scoping of variables,the scoping of variables,and the lifetime of variables.and the lifetime of variables.