Ch 10: More on Variables and Subroutines CP212 Winter 2012.

Slides:



Advertisements
Similar presentations
Integrated Business Applications with Databases (D3) Jenny Pedler
Advertisements

ISOM3230 Business Applications Programming
Chapter 7 Introduction to Procedures. So far, all programs written in such way that all subtasks are integrated in one single large program. There is.
Modeling using VBA. Covered materials -Userforms -Controls -Module -Procedures & Functions -Variables -Scope.
AE6382 VBA - Excel l VBA is Visual Basic for Applications l The goal is to demonstrate how VBA can be used to leverage the power of Excel u VBA syntax.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Arrays. What is an Array? An array is a way to structure multiple pieces of data of the same type and have them readily available for multiple operations.
1 Visual Basic Programming II Lecture 3 MIS233 Instructor – Larry Langellier.
Lecture Roger Sutton CO331 Visual Programming 12: One-dimensional Arrays 1.
Writing General Procedures Often you will encounter programming situations in which multiple procedures perform the same operation This condition can occur.
VBA Modules, Functions, Variables, and Constants
Sub Programs To Solve a Problem, First Make It Simpler.
Case, Arrays, and Structures. Summary Slide  Case Structure –Select Case - Numeric Value Example 1 –Select Case - String Value Example  Arrays –Declaring.
Arrays Array of Controls: several controls, of the same type (Class: a prototype for an object indicating the properties and methods), that have the same.
1 Introduction to Computers and Programming Quick Review What is a Function? A module of code that performs a specific job.
PSU CS 106 Computing Fundamentals II VB Subprograms & Functions HM 4/29/2008.
Promoting Code Reuse Often in programming, multiple procedures will perform the same operation IN OTHER WORDS – the same piece of code will do the same.
Arrays Array of Controls: several controls, of the same type (Class: a prototype for an object indicating the properties and methods), that have the same.
VBA & Excel Barry L. Nelson IEMS 465 Fall Quarter 2003.
1 CS101 Introduction to Computing Lecture 29 Functions & Variable Scope (Web Development Lecture 10)
Apply Sub Procedures/Methods and User Defined Functions
Using Data Active Server Pages Objectives In this chapter, you will: Learn about variables and constants Explore application and session variables Learn.
 Excel – Basic Elements  Using Macros  Excel VBA Basics  Excel VBA Advanced.
IE 212: Computational Methods for Industrial Engineering
Ch 11: Userforms CP212 Winter Topics Designing User Forms o Controls Setting Properties o Tab Order o Testing Writing Event Handlers o Userform_Initialize.
1 Subroutines and Functions Chapter 6 in Deitel, Deitel and Nieto.
1 Visual Basic for Applications (VBA) for Excel Prof. Yitzchak Rosenthal.
Why to Create a Procedure
Using Arrays and File Handling
CSCI 3327 Visual Basic Chapter 6: Methods: A Deeper Look UTPA – Fall 2011.
Chapter 17: Arrays Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
Procedures and Functions Computing Module 1. What is modular programming? Most programs written for companies will have thousands of lines of code. Most.
Arrays and 2D Arrays.  A Variable Array stores a set of variables that each have the same name and are all of the same type.  Member/Element – variable.
VB Games: Preparing for Memory Brainstorm controls & events Parallel structures (again), Visibility, LoadPicture, User-defined procedures, Do While/Loop,busy.
Arrays Code: Arrays Controls: Control Arrays, PictureBox, Timer.
MS Visual Basic Applications Walter Milner. Event-driven programming Standard approach for GUIs Contrast with old character interfaces – program determines.
Variables,Constants and Data types Variables temporarily stores values during the execution of an application Variables have a name and data type Declare.
IMS 3253: Subroutines 1 Dr. Lawrence West, MIS Dept., University of Central Florida Topics Procedures Subroutines Parameters –By Value.
CSC 162 Visual Basic I Programming. Array Parameters and Sorting Array Parameters –Entire Arrays –Individual Elements Sorting –Bubble Sort.
Overview of VBA Programming & Syntax. Programming With Objects u Objects –Properties: attributes or characteristics of an object (e.g., font size, color,
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC PROGRAMMING FUNDAMENTALS Bilal Munir Mughal 1 Chapter-8.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
ME 142 Engineering Computation I Using Subroutines Effectively.
Procedures Subs and Functions. Procedures Before OOP, subroutines were the primary high-level way to organize a program. In OOP, this role has been taken.
CHAPTER 9 PART II. MULTIDIMENSIONAL ARRAYS Used to represent tables of values arranged in rows and columns. Table element requires two indexes: row and.
ME 142 Engineering Computation I Using Subroutines Effectively.
Debugging, Static Variables, ByRef, ByValue Chapt. 6 in Deitel, Deitel and Nieto.
Programming games in Visual Basic Review programming & VB topics Insertion sort. Best times. Generate questions & answer patterns for quiz Lab/Homework:
Controlling Program Flow with Decision Structures.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
1 CS 106 Computing Fundamentals II Chapter 28 “Scope” Herbert G. Mayer, PSU CS Status 7/14/2013 Initial content copied verbatim from CS 106 material developed.
More on Variables and Subroutines. Introduction Discussion so far has dealt with self- contained subs. Subs can call other subs or functions. A module.
Starting Out with Visual Basic.NET 2 nd Edition Chapter 6 Sub Procedures And Functions.
Chapter 15: Sub Procedures and Function Procedures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University.
Week 1 Lecture 1 Slide 1 CP2028 Visual Basic Programming 2 “The VB Team” Copyright © University of Wolverhampton CP2028 Visual Basic Programming 2 v Week.
National Diploma Unit 4 Introduction to Software Development Procedures and Functions.
Subroutines and Functions Chapter 6. Introduction So far, all of the code you have written has been inside a single procedure. –Fine for small programs,
Lecture 6 – Working with VBA Sub Procedures Dr Joanna Wyrobek 1.
Sub Procedures and Functions Visual Basic. Sub Procedures Slide 2 of 26 Topic & Structure of the lesson Introduction to Modular Design Concepts Write.
Scope. Scope of Names In a small program written by one person, it is easy to be sure that each variable has a unique name In a large program, or one.
Lecture 7 Methods (functions and subroutines) Parameter Passing
Programming Right from the Start with Visual Basic .NET 1/e
VBA - Excel VBA is Visual Basic for Applications
Spreadsheet-Based Decision Support Systems
Sub Procedures and Functions
CS285 Introduction - Visual Basic
If, Subroutines and Functions
Methods.
Chapter 8 - Functions and Functionality
CPS125.
Presentation transcript:

Ch 10: More on Variables and Subroutines CP212 Winter 2012

Topics Subroutines Functions Modular programming o 3 Main Benefits Variable and Subroutine Scope Using and Passing Parameters Module level "Global" variables Passing arrays The Workbook_Open event handler Generating Random Numbers (Ex. 10.4)

Scope A variable is created in a sub can only be used in that sub. It has limited scope: sub-level scope. Known as a local variable. Sub myFirstSub() Dim score As Integer score = 3 Msgbox score End Sub Sub mySecondSub() Dim score As Integer score = 4 Msgbox score End Sub Different variables, different location in memory.

Module-Level Scope If you want subs to share a variable, declare it outside of a sub This makes it a module-level variable Every sub in the module can access the variable Option Explicit Dim userName As String Sub myFirst() userName = “Biff” End Sub Sub mySecond() Msgbox userName End Sub

Visibility Levels Keywords such as Public or Private are used to indicate their visibility, aka, their scope. userName has project-level scope, all modules can access it income has Module Level scope - only accessed in this module. This is the same as Private. To limit visibility to subs in Module1, use "Private" instead of "Public". Private - good for "helper" subs that have limited use or will only be called by subs in that module

Visibility Levels Using Public makes variable available to the entire Project (all modules) Using Dim outside of subroutines makes Module-Level Scope (same as Private). Subroutines can be either Public or Private as well.

Visibility Levels See Scope in Chapter10ExamplesXXXX2012.xlsm

Modularity break down a large problem into smaller ones each subroutine should handle a small, complete problem a program then consists of many subroutines and functions each sub can call other functions or subs Sub MainProgram() ' The main program calls other subs Call GetInput Call ProcessData Call DisplayResults End Sub The keyword CALL is optional, but it helps illustrate what is going on.

3 Benefits of Modular Programming Easier to read Easier to debug Software reuse Ch10 shows how the Travelling Salesperson program from the last chapter has been broken down into smaller subroutines.

A Modular Program modularity.xls in MyLearningSpace Option Explicit ' Project level variables Public userName As String Public Sub MainProgram() GatherData ProcessTheMessage DisplayGreeting End Sub Private Sub GatherData() userName = InputBox("What is your name?", "Greetings", "-user-") End Sub Private Function Greeting(s As String) As String Greeting = "Hello there, " & s End Function Private Sub ProcessTheMessage() MsgBox "The length of the message is now " & _ Len(Greeting(userName)) & " characters.", _ vbOKOnly + vbInformation, _ Title:="Results" End Sub

Passing Arrays pretty important, don't let the () mess you up Write a subroutine that will sort an array of any size Sub CallingSub() Dim names(100) As String For i = 1 to 100 names(i) = Range("Names").Cells(i).Value Next SortNames names '<---- Pass the array to the another sub ' Call SortNames(names) ' can also be used End Sub

The Sub Sub SortNames(names() As String) Dim nNames As Integer nNames = UBound(names) ' determines the upper index limit ' More sorting code goes here End Sub UBound returns the largest index of the array, ie: ArraySize - 1 if using 0 based arrays (the default) Can also use LBound to determine the lowest bound for the array

3 Minute Challenge Write a subroutine that takes an array of any size and prints all the values. Take 3 minutes. GO! Solution on next slide.

Using LBound and UBound Sub PrintArray(theArray() As String) Dim i As Integer ' Safer to check LBound and UBound ' in case there is Base 0 or Base 1 confusion For i = LBound(theArray) To UBound(theArray) MsgBox theArray(i) Next End Sub

Function Subroutines Function CircleArea (r As Single) As Single If r > 0 Then CircleArea = * r * r Else CircleArea = 0 End If End Function Can be used in VBA and in the Spreadsheet like a built-in function If saved to personal.xlsb, you'll have to call it with =personal.xlsb.CircleArea(A5)

Generating Random Numbers See Example Functions.xlsm use Application.Volatile to ensure that different values are calculated each time the sheet recalculates o matches the operation of the RAND spreadsheet function VBA RND function generates a value between 0 and 1 with a uniform distribution

Workbook_Open Event Handler code placed in this subroutine runs when the workbook is opened not placed in a Module, its placed in the ThisWorkbook code window lots of other Workbook events worth exploring

References For more details, check out: Recommended Exercises Chapter , 3, 4, 6, 8, 15, 16, 19