Computer Science Lab Exercise 2

Similar documents
Computer Science Lab Exercise 1

Optimization in One Variable Using Solver

You can record macros to automate tedious

Introduction to macros

Microsoft Excel 2007 Macros and VBA

VBA Excel 2013/2016. VBA Visual Basic for Applications. Learner Guide

Validate and Protect Data

Extending the Unit Converter

Functions in Excel. Structure of a function: Basic Mathematical Functions. Arithmetic operators: Comparison Operators:

M i c r o s o f t E x c e l A d v a n c e d. Microsoft Excel 2010 Advanced

INTRODUCTION TO MICROSOFT EXCEL: DATA ENTRY AND FORMULAS

DOING MORE WITH EXCEL: MICROSOFT OFFICE 2013

Workbook Also called a spreadsheet, the Workbook is a unique file created by Excel. Title bar

Microsoft Office Illustrated. Getting Started with Excel 2007

COPYRIGHTED MATERIAL. Making Excel More Efficient

Creating a Spreadsheet by Using Excel

Basics: How to Calculate Standard Deviation in Excel

Jump Right In! Essential Computer Skills Using Microsoft 2013 By Andrews, Dark, and West

To complete this workbook, you will need the following file:

Excel Macros, Links and Other Good Stuff

Maximizing the Power of Excel With Macros and Modules

= 3 + (5*4) + (1/2)*(4/2)^2.

Benchmark Excel 2010 Level 1, Chapter 5 Rubrics

Geology Geomath Estimating the coefficients of various Mathematical relationships in Geology

DOING MORE WITH EXCEL: MICROSOFT OFFICE 2010

Excel Forecasting Tools Review

Computer Applications Data Processing FA 14

Chapter 3: The IF Function and Table Lookup

Lab 7 Macros, Modules, Data Access Pages and Internet Summary Macros: How to Create and Run Modules vs. Macros 1. Jumping to Internet

Getting started 7. Writing macros 23

download instant at

Microsoft Excel Level 2

Excel Community SAMPLE CONTENT

Quantitative Techniques: Laboratory 4 Revision

Table of Contents Data Validation... 2 Data Validation Dialog Box... 3 INDIRECT function... 3 Cumulative List of Keyboards Throughout Class:...

DATA 301 Introduction to Data Analytics Microsoft Excel VBA. Dr. Ramon Lawrence University of British Columbia Okanagan

This chapter is intended to take you through the basic steps of using the Visual Basic

Creating If/Then/Else Routines

Microsoft Excel 2010 Training. Excel 2010 Basics

CS 105 Lab As a review of what we did last week a. What are two ways in which the Python shell is useful to us?

Tutorial 9. Review. Data Tables and Scenario Management. Data Validation. Protecting Worksheet. Range Names. Macros

How to Remove Duplicate Rows in Excel

BASIC EXCEL SYLLABUS Section 1: Getting Started Section 2: Working with Worksheet Section 3: Administration Section 4: Data Handling & Manipulation

Excel Tip: How to create a pivot table that updates automatically

A Tutorial for Excel 2002 for Windows

Open Learning Guide. Microsoft Excel Introductory. Release OL356v1

lab MS Excel 2010 active cell

Working with Basic Functions. Basic Functions. Excel 2010 Working with Basic Functions. The Parts of a Function. Page 1

Using macros enables you to repeat tasks much

Range Objects and the ActiveCell

Introduction to Microsoft Excel

Module Four: Formulas and Functions

EDIT202 Spreadsheet Lab Prep Sheet

BASIC MACROS IN EXCEL Presented by IGNACIO DURAN

Project 4 Financials (Excel)

3. (1.0 point) To quickly switch to the Visual Basic Editor, press on your keyboard. a. Esc + F1 b. Ctrl + F7 c. Alt + F11 d.

Excel Pivot Tables & Macros

EXCEL BASICS: MICROSOFT OFFICE 2007

INFORMATION SHEET 24002/1: AN EXCEL PRIMER

DOWNLOAD PDF MICROSOFT EXCEL ALL FORMULAS LIST WITH EXAMPLES

CALCULATE NPV USING EXCEL

Microsoft Office Excel Use Excel s functions. Tutorial 2 Working With Formulas and Functions

Using Microsoft Excel

Advanced Financial Modeling Macros. EduPristine

DOWNLOAD PDF VBA MACRO TO PRINT MULTIPLE EXCEL SHEETS TO ONE

Excel Level 3 - Advanced

WEEK NO. 12 MICROSOFT EXCEL 2007

CpSc 1011 Lab 4 Formatting and Flow Control Windchill Temps

Window (further define the behaviour of objects)

Performing Basic Calculations

Practical 2: Using Minitab (not assessed, for practice only!)

Chapter-2 Digital Data Analysis

Formulas in Microsoft Excel

Reference Services Division Presents. Excel Introductory Course

dark star Excelsior User s guide A Year 2000 Auto-Renovation Tool

UW Department of Chemistry Lab Lectures Online

Unit 3 Fill Series, Functions, Sorting

Excel Foundation (Step 2)

Microsoft Excel 2010

Unit 3 Functions Review, Fill Series, Sorting, Merge & Center

Intermediate Excel Training Course Content

CS 200. Lecture 07. Excel Scripting. Miscellaneous Notes

Documentation of DaTrAMo (Data Transfer- and Aggregation Module)

Section 3. Formulas. By the end of this Section you should be able to:

Using Basic Formulas 4

Learning Excel VBA. Creating User Defined Functions. ComboProjects. Prepared By Daniel Lamarche

Contents. Session 2. COMPUTER APPLICATIONS Excel Spreadsheets

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

DOWNLOAD PDF MICROSOFT OFFICE POWERPOINT 2003, STEP BY STEP

EXCEL PRACTICE 5: SIMPLE FORMULAS

Microsoft Excel 2007

Excel Lesson 3 USING FORMULAS & FUNCTIONS

Skill Set 3. Formulas

Math 1525 Excel Lab 1 Introduction to Excel Spring, 2001

EXCEL BASICS: MICROSOFT OFFICE 2010

Assignment 2: Temperature Class

CS 200. Lecture 07. Excel Scripting. Excel Scripting. CS 200 Fall 2016

CS 200. Lecture 07. Excel Scripting. Miscellaneous Notes

Create formulas in Excel

Visual basic tutorial problems, developed by Dr. Clement,

Transcription:

osc 127 Lab 2 1 of 10 Computer Science 127 - Lab Exercise 2 Excel User-Defined Functions - Repetition Statements (pdf) During this lab you will review and practice the concepts that you learned last week as well as learn a few more Visual Basic statements that will increase your ability to create powerful Excel user-defined functions (UDFs). Review We saw during the last lab that in the case of simple calculations, the tools you have always used with Excel are sufficient to develop your spreadsheets. However, when you build spreadsheets with complicated calculations Excel provides user-defined functions (UDFs), a powerful tool that allows you to build your own customized functions. Here are a few of the key things that were learned last week: Visual Basic (VB) is a computer programming language used to code (specify) what a UDF does and returns. UDFs are written within a Visual Basic Module (VB Module) within the Visual Basic Editor (VB Editor). To toggle between a spreadsheet and the VB editor press, alt-f11. UDFs, just like Excel's built-in functions, return a value to the spreadsheet formula that calls the function. UDFs can have arguments that are passed into the function when they are called. These arguments are called actual parameters in the Excel spreadsheet formula (for example, B4 and C4 in the formula =PROFIT(B4,C4)). In the VB Module that defines the UDF, these arguments are called formal parameters and are specified in the function header for the UDF. For example, in the function header, Function PROFIT(revenue, expenses), revenue and expenses are the formal parameters that correspond to the actual parameters, B4 and C4 respectively. In this example, the values contained in cells B4 and C4 would be assigned to the variables revenue and expenses, respectively, within the UDF. VB code often contains a statement that looks something like "sum = sales + x * 2 + 100". Although this statement looks just like an equation we might see in math where "=" is expressing the equivalence of the right side to the left side, this statement is an assignment statement. The "=" in VB is the assignment operator and means that the value calculated on the right side of the "=" should be assigned to the variable on the left side of the "=". We should regard variables as named storage locations for data. In this example, the variable sum would store the calculated value. The VB statements that comprise a UDF are executed in a top-to-bottom order until a value is assigned to a variable that has the same name as the function. This value that is assigned, is the return value for the UDF, and the UDF immediately returns to the calling Excel formula. Review Exercise: Create a temperature converter UDF called TEMPCONV. In this example, we will create a temperature converter UDF to convert a temperature in degrees Fahrenheit to degrees Celsius. The formula for such a conversion is straightforward, and probably wouldn't warrant the use of a UDF. However, during this example, we'll expand the functionality of TEMPCONV so that it indeed becomes a complicated function. Follow the instructions indicated below to build the first version of TEMPCONV. 1. Open Excel 2010. Adjust the security settings for your file. Select File, then Options to open the Excel Options dialog box. Then select Trust Center, then Trust Center Settings to open the Trust Center dialog box. Then select Macro Settings and then enable all macros and check Trust access to the VBA project object model. Click OK to close the Trust Center dialog box and then click OK again to close the Excel Options dialog box.

CoSc 127 Lab 2 2 of 10 2. Open an Excel workbook and enter the data shown in the table below. Save the file as a Macro-Enabled Workbook using Name-Lab2.xlsm as the filename. Use your first name and last initial in place of Name. For example, I would save this file as AlanK-Lab2.xlsm. 3. Next, we will start the process of creating the UDF. Open the VB Editor by pressing alt-f11 (recall that alt-f11 is a toggle to move back and forth between your spreadsheet and the VB Editor). The VB Editor window will look something like this: 4. To open a VB Module, select Module from the Insert menu:

CoSc 127 Lab 2 3 of 10 A VB Module will appear in the right side of the window: 5. Remember that it is within this white area on the right that we will create the user-defined function. Now that we have a VB module open, we can code the TEMPCONV UDF. Type the VB code for the TEMPCONV function into the VB Module as shown below: 6. Now lets try using our UDF. Return to your spreadsheet by selecting it from the taskbar or by pressing alt-f11. Enter the formula shown in cell B5.

osc 127 Lab 2 4 of 10 7. Press enter and copy the formula to B6:B13: If you made a mistake and fixed it, you will need to ask Excel to recalculate the spreadsheet. Recall that you can do this by pressing F9. Change the number of decimal places to 2 and Save your file. Exercise: Adding functionality to a UDF Let's add some additional functionality to our UDF. For example, it would be useful if our UDF could also convert from Celsius to Fahrenheit as well as Fahrenheit to Celsius. However, adding such functionality poses a problem for the UDF. Specifically, how does the UDF know which conversion the user wants? Somehow some information needs to be passed into the UDF so that the UDF knows which formula to perform. A reasonable approach would be to add another formal parameter to the UDF. The second parameter would allow the user to indicate which conversion should be done. For example, suppose a user wants to convert 50 degrees Celsius to Fahrenheit, the user could call the function by indicating =TEMPCONV(50,1) in the Excel formula. If the user wants to convert 50 degrees Fahrenheit to Celsius, the user could call the function by indicating =TEMPCONV(50,0) in the Excel formula. The UDF could now distinguish which conversion is desired, by testing the value of the second formal parameter. Follow the steps below to add this extra functionality. 1. Add columns to your spreadsheet as shown below:

CoSc 127 Lab 2 5 of 10 2. Return to the VB Module by pressing alt-f11. Modify the TEMPCONV function as shown below. Here we see that we use the If..Then..Else VB statement to test the value of the formal parameter conv. If the actual parameter associated with conv is 0, then the condition in the If..Then..Else statement will be true, causing the first calculation to be the one that is returned. If conv is not equal to 0, then the second calculation will be returned. 3. Return to your spreadsheet and enter the formula shown below into cell E5. 4. Pressing enter gives this result:

CoSc 127 Lab 2 6 of 10 Although we get the expected value in cell E5, the values in cells B5:B13 now indicate "#VALUE!". Unfortunately, what we inadvertently did was change the structure of the TEMPCONV UDF - it now takes two actual parameters. As a result, we are no longer using the UDF correctly in B5:B13. When we pressed enter, we entered a new formula into a cell, so Excel recalculated the spreadsheet and noticed that there is no function called TEMPCONV that takes just a single parameter. 5. To fix the problem with the initial conversion, enter the formula shown below into B5. Press enter and copy B5 to B6:B13. Also copy E5 to E6:E13. Your spreadsheet will now give the expected values as the formulas are now calling the TEMPCONV UDF correctly. 6. Save your spreadsheet.

osc 127 Lab 2 7 of 10 Visual Basic Statements for Performing Repetition Recall from last week that a computer program is a sequence of programming statements that exactly follow the specific structure (or syntax) of a programming language. These statements ask the computer (or application) to do something useful. By default the program statements that you create in VB are executed using so-called sequential flow of control. There are three flows of control. The first is sequential flow, which means that each statement is executed immediately after the previous statement (usually located above the statement in a text editor). The second flow of control is called conditional flow. Conditional flow occurs when a mechanism provides the ability to execute a statement only under certain conditions. An example of such a mechanism is any one of the flavours of the If..Then statements. The third flow of control is called repetition flow. Repetition flow occurs when a mechanism provides the ability to execute a set of statements repeatedly. Programming languages often provide multiple ways of repeating a set of statements. We will examine one of the ways provided by VB. A statement that facilitates the repetition of statements is often referred to as a loop. Experimenting with Loops No study of computer programming would be complete without discussing at least one mechanism for repeating statements. Although you will find conditional flow to be the most used flow of control (i.e. If..Then statements) there are certain things that are simplified with the ability to perform repetition. In fact, there are some things we simply cannot do without a mechanism for repeating statements. The following exercises will give us a little practice with incorporating a loop into a UDF. Exercise: Calculating the Sum of a Sequence of Numbers In Visual Basic, the so-called Do While statement is used to repeat a set of statements. The syntax below describes the Do While statement. Do While condition Put statements to be executed if condition is true, here Loop When program execution arrives at this statement the condition is tested. If the condition is true, the statements between the Do While condition line and the Loop line are executed repeatedly until the condition becomes false. Once the condition becomes false the flow of control returns to sequential flow immediately following the Loop line. For example, suppose these statements appeared within the loop: then statements are executed as follows: Is condition true? (If yes, start executing the next line. If no, start executing immediately after the Loop line.) Is condition true? (If yes, start executing the next line. If no, start executing immediately after the Loop line.)

CoSc 127 Lab 2 8 of 10 Is condition true? (If yes, start executing the next line. If no, start executing immediately after the Loop line.)... Is condition true? (If yes, start executing the next line. If no, start executing immediately after the Loop line.) Is condition true? (If yes, start executing the next line. If no, start executing immediately after the Loop line.) Provided that one of the three statements changes the condition, eventually the answer to the question "Is condition true?" will be no and the loop will terminate. This helps to highlight why the term loop is often used in this context. The execution within a loop proceeds down, line-by-line, until the keyword Loop is executed, which says return to to the start of the loop and retest the condition. Let's create a UDF, called SUMMER, to calculate the sum of numbers between two user-specified numbers. This UDF will calculate all numbers from one specified parameter to another. For example, if the user called the function using =SUMMER(15,22) this function would return the result of the expression 15+16+17+18+19+20+21+22. As the user can give any two numbers as actual parameters we cannot know how many numbers should be in the expression. As a result, we will use a loop rather than trying (in vane) to construct a single lengthy expression. 1. 2. If not already open, open your Name-Lab2.xlsm Excel workbook. Press alt-f11 to toggle to the VB Editor window. Open a VB Module and enter the UDF code shown here: Let's examine this code. The first and last lines follow the familiar structure, with low and high being two formal parameters. The second line Sum = 0 is an assignment statement assigning the value of 0 to the variable Sum. The variable Sum is going to act like an adding machine. Each cycle through the loop, we will be adding another value to Sum. Sum will be accumulating the values. The third line is the start of the loop and sets up the loop by specifying the condition under which the contents of the loop should be executed.

CoSc 127 Lab 2 9 of 10 Lines four and five are the contents of the loop. These lines will be executed once for every cycle of the loop. Line four, Sum = Sum + low, increases the value of Sum by whatever value is stored in low. Line five, low = low +1, increases the value stored in variable low by 1. Repeating these two statements will have the effect of adding the values low, low+1, low+2, low+3,..., high. As the variable low is increased by 1 after each cycle through the loop, eventually it will exceed the value stored in the variable high. That is the cycle at which flow control jumps out of the loop. Line six, Loop, specifies the bottom of the loop - the statement at which control of execution is automatically returned to the top of the loop (to retest the condition, low <= high, to see if the contents of the loop should be executed again). Line seven, SUMMER = Sum, is the return statement. Recall that when a value is assigned to a variable with the same name as the function, that value represents the value that is returned from the function. Once a return value is assigned, the function stops executing. 3. Return to your spreadsheet and try using the formula: 4. Pressing enter here yields this result: This is the expected result as 10 + 11 + 12 + 13 + 14 + 15 equals 75. 5. Save your workbook. Exercises: 1. 2. Try adding a function very similar to SUMMER called AlternateSUMMER to your Name-Lab2.xls file that sums every other number between two user-specified numbers. For example, if a user enters the formula =AlternateSUMMER(10,15), the function should return the result of the expression 10 + 12 + 14. If a user enters the formula =AlternateSUMMER(10,16), the function should return the result of the expression 10 + 12 + 14 + 16. If a user enters the formula =AlternateSUMMER(9,16), the function should return the result of the expression 9 + 11 + 13 + 15. After examining the original code, you will see that your new function is almost identical to the original function. Besides changing the last line to "AlternateSummer = sum", there is just one line within the function that will need to change. Experiment with this function to see if you can find it. Add another function to your Name-Lab2.xls file called flowconv. This function should be able to convert a flow specified in cubic feet per second (cfs) to cubic metres per second (cms), and also convert from cms to cfs. Follow the technique that we used in the earlier part of the lab to create this function. For your reference, 1 cubic foot/second is equal to 0.028317 cubic meters/second. Submitting your Work

When you complete these exercises call your instructor over to check your work. If your instructor asks, submit your work through Blackboard email. CoSc 127 Lab 2 10 of 10