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)

Slides:



Advertisements
Similar presentations
1 VBScript Session What we learn last session?
Advertisements

Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Chapter 6, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 6 Sub Procedures And Functions.
Chapter 4 Parameters and Overloading. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 4-2 Learning Objectives Parameters Call-by-value Call-by-reference.
Lists, Loops, Validation, and More
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
Writing Pseudocode And Making a Flow Chart A Number Guessing Game
Tutorial 9 – Creating On-Screen Forms Using Advanced Table Techniques
XP New Perspectives on Microsoft Office Word 2003 Tutorial 6 1 Microsoft Office Word 2003 Tutorial 6 – Creating Form Letters and Mailing Labels.
XP New Perspectives on Microsoft Office Word 2003 Tutorial 7 1 Microsoft Office Word 2003 Tutorial 7 – Collaborating With Others and Creating Web Pages.
Jeopardy Q 1 Q 6 Q 11 Q 16 Q 21 Q 2 Q 7 Q 12 Q 17 Q 22 Q 3 Q 8 Q 13
Jeopardy Q 1 Q 6 Q 11 Q 16 Q 21 Q 2 Q 7 Q 12 Q 17 Q 22 Q 3 Q 8 Q 13
DIVIDING INTEGERS 1. IF THE SIGNS ARE THE SAME THE ANSWER IS POSITIVE 2. IF THE SIGNS ARE DIFFERENT THE ANSWER IS NEGATIVE.
Excel Functions. Part 1. Introduction 2 An Excel function is a formula or a procedure that is performed in the Visual Basic environment, outside the.
Chapter 7: Arrays In this chapter, you will learn about
Variables Conditionals Boolean Expressions Conditional Statements How a program produces different results based on varying circumstances if, else if,
Chair of Software Engineering Einführung in die Programmierung Introduction to Programming Prof. Dr. Bertrand Meyer Exercise Session 5.
Data Structures Using C++
Modern Programming Languages, 2nd ed.
3 Logic The Study of What’s True or False or Somewhere in Between.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 12 – Security Panel Application Introducing.
1 What is JavaScript? JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A scripting language is a lightweight.
User Defined Functions
1 Welcome to SAPS Webmail. 2 Things we will learn about: 1. Login to mail.
CREATING A PAYMENT REQUEST FOR A NEW VENDOR
4 Oracle Data Integrator First Project – Simple Transformations: One source, one target 3-1.
Subprograms Functions Procedures. Subprograms A subprogram separates the performance of some task from the rest of the program. Benefits: “Divide and.
A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
1 POWERPOINT May 2004 To move the text box - move the mouse over the border of the text box, and once the 4-way arrow appear – click and drag the box.
Lecture 6: Software Design (Part I)
Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1.
CSM18 Visual Basic Section1 Department of Computing UniS 1 CSM18 Interactive Computing Introduce Visual Basic language - provides excellent facilities.
Procedures. 2 Procedure Definition A procedure is a mechanism for abstracting a group of related operations into a single operation that can be used repeatedly.
1 HomeHome Log in Calculators Navigation Review Screen Go to Next Section Seal Codes Ending the TestLog inCalculatorsNavigationReview ScreenGo to Next.
CS 240 Computer Programming 1
25 seconds left…...
Spring Semester 2013 Lecture 5
Solving the eValue Rubik’s cube
Benchmark Series Microsoft Excel 2010 Level 1
Lilian Blot CORE ELEMENTS SELECTION & FUNCTIONS Lecture 3 Autumn 2014 TPOP 1.
Testing Hypotheses About Proportions
Chapter 13 – Introduction to Classes
Introduction to Recursion and Recursive Algorithms
CMPT 100 : INTRODUCTION TO COMPUTING TUTORIAL #5 : JAVASCRIPT 2 GUESSING GAME By Wendy Sharpe 1.
Chapter 8 Improving the User Interface
User Defined Functions Lesson 1 CS1313 Fall User Defined Functions 1 Outline 1.User Defined Functions 1 Outline 2.Standard Library Not Enough #1.
 Functions breakdown: Functions purpose Modularity Declaring and defining a function Calling a function Parameter passing Returning a value Reusability.
Chapter 9: Using Classes and Objects. Understanding Class Concepts Types of classes – Classes that are only application programs with a Main() method.
1 Lecture 16:User-Definded function I Introduction to Computer Science Spring 2006.
1 CS 106, Winter 2009 Class 10, Section 4 Slides by: Dr. Cynthia A. Brown, Instructor section 4: Dr. Herbert G. Mayer,
1 CS 106, Winter 2009 Class 11, Section 4 Slides by: Dr. Cynthia A. Brown, Instructor section 4: Dr. Herbert G. Mayer,
VBA Modules, Functions, Variables, and Constants
Example 2.
Apply Sub Procedures/Methods and User Defined Functions
Microsoft Visual Basic 2012 Using Procedures and Exception Handling CHAPTER SEVEN.
Why to Create a Procedure
CPS120: Introduction to Computer Science Decision Making in Programs.
CPS120: Introduction to Computer Science Functions.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC PROGRAMMING FUNDAMENTALS Bilal Munir Mughal 1 Chapter-8.
JavaScript, Fourth Edition
1 Chapter 3 – Examples The examples from chapter 3, combining the data types, variables, expressions, assignments, functions and methods with Windows controls.
31/01/ Selection If selection construct.
Controlling Program Flow with Decision Structures.
National Diploma Unit 4 Introduction to Software Development Procedures and Functions.
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.
Subprograms Functions Procedures.
Introduction to Visual Programming
Presentation transcript:

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) 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 2

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 3

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 4

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 5

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 6

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 7

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) 8

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… 9

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. 10

Parameters Sub 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 11

More on Formal Parameters Sub 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 12

Procedure Body Sub PrintAnswer(ByVal param1 As Double, ByVal param2 As Double) Dim answer As Double 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 13

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) 14

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 15

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 = 5 Call PrintAnswer(x,y) sets param1 = x and param2 = y, whatever the values of x and y happen to be 16

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 17

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 + param2 End Function 18

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). 19 ComputeAnswer = param1 + param2

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) 20

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) 21

A Picture of the Control Flow for a Procedure Call Some program code Procedure call More program code Procedure code Set parameter values 22 Return value (function)

Let’s look the procedure demo

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 24

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 25

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 26

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. 27

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 28