15 Aug 20111 Visual Basic for Applications Programming language Very similar to Visual Basic Embedded in Microsoft Office applications “Object oriented”

Slides:



Advertisements
Similar presentations
MATH 224 – Discrete Mathematics
Advertisements

RAPTOR Syntax and Semantics By Lt Col Schorsch
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.
Procedural programming in Java
Flow Charts, Loop Structures
Programming TBE 540 Farah Fisher. Objectives After viewing this presentation, the learner will be able to… Given a task, create pseudocode Given pseudocode,
CS0004: Introduction to Programming Repetition – Do Loops.
The Little man computer
 Control structures  Algorithm & flowchart  If statements  While statements.
Loops (Part 1) Computer Science Erwin High School Fall 2014.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
Computer Science 1620 Loops.
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure.
Classes, methods, and conditional statements We’re past the basics. These are the roots.
Computer Science 1620 Programming & Problem Solving.
Complexity (Running Time)
CS 106 Introduction to Computer Science I 09 / 28 / 2007 Instructor: Michael Eckmann.
Adding Automated Functionality to Office Applications.
Exploring Microsoft Excel 2002 Chapter 8 Chapter 8 Automating Repetitive Tasks: Macros and Visual Basic for Applications By Robert T. Grauer Maryann Barber.
ALGORITHMS AND FLOWCHARTS
PROGRAMMING, ALGORITHMS AND FLOWCHARTS
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Looping Exercises Deciding Which Loop to Use At this.
IE 212: Computational Methods for Industrial Engineering
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Chapter 2 - Algorithms and Design
08/10/ Iteration Loops For … To … Next. 208/10/2015 Learning Objectives Define a program loop. State when a loop will end. State when the For.
COMPUTER PROGRAMMING. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may repeat code.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Using Visual Basic for Applications in Microsoft Project Sean Vogel.
CRE Programming Club - Class 4 Robert Eckstein and Robert Heard.
CS285 Visual Basic 2 Department of Computing UniS 1 Statements in Visual Basic A statement is the fundamental syntactical element of a program smallest.
PROBLEM SOLVING WITH LOOPS Chapter 7. Concept of Repetition Structure Logic It is a computer task, that is used for Repeating a series of instructions.
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
CSC Intro. to Computing Lecture 12: PALGO. Announcements Homework #3 solutions available  Download from Blackboard/web Quiz #3 will be in class.
Review, Pseudocode, Flow Charting, and Storyboarding.
6.2 For…Next Loops General Form of a For…Next Loop
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
22/11/ Selection If selection construct.
I Power Higher Computing Software Development High Level Language Constructs.
Chapter 16: Programming Structures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University Name.
ITI 1120 Lab #5 Contributors: S. Boyd, R. Plesa, A. Felty, D. Inkpen, A. Williams, D. Amyot.
Lab 6 (2) Arrays ► Lab 5 (1) Exercise Review ► Array Concept ► Why Arrays? ► Array Declaration ► An Example of Array ► Exercise.
Copyright © 2001 by Wiley. All rights reserved. Chapter 6: Using Arrays Control Arrays List Arrays Finding Items in Arrays Multiple Forms 2-Dimensional.
Iteration Hussein Suleman UCT Dept of Computer Science CS115 ~ 2004.
Repetition. Loops Allows the same set of instructions to be used over and over again Starts with the keyword loop and ends with end loop. This will create.
REPETITION STATEMENTS - Part2 Structuring Input Loops Counter-Controlled Repetition Structure Sentinel-Controlled Repetition Structure eof()-Controlled.
Think Possibility 1 Iterative Constructs ITERATION / LOOPS C provides three loop structures: the for-loop, the while-loop, and the do-while-loop. Each.
CRE Programming Club - Class 4 Robert Eckstein and Robert Heard.
Controlling Program Flow with Decision Structures.
Flow of Control: Loops Module 4. Objectives Design a loop Use while, do, and for in a program Use the for-each with enumerations Use assertion checks.
ALGORITHMS AND FLOWCHARTS. Why Algorithm is needed? 2 Computer Program ? Set of instructions to perform some specific task Is Program itself a Software.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Programming Mehdi Bukhari.
User-Defined Functions
ALGORITHMS AND FLOWCHARTS
Exploring Microsoft Excel
Java Programming Loops
T. Jumana Abu Shmais – AOU - Riyadh
Algorithm Discovery and Design
ALGORITHMS AND FLOWCHARTS
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Language Constructs Construct means to build or put together. Language constructs refers to those parts which make up a high level programming language.
Java Programming Loops
Introduction to Computer Programming IT-104
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

15 Aug Visual Basic for Applications Programming language Very similar to Visual Basic Embedded in Microsoft Office applications “Object oriented” Automate Office operations Build macros and functions We will only learn enough VBA to write simple functions

15 Aug Program Program = code call = run = execute = launch = start List of instructions Input Got at program’s start Asked to the user Got from Excel table Does some predetermined operations Output Written in Debug window or Message Box Written in Excel table “returned” like Excel functions

15 Aug Variables Memory places to store values Types Integer numbers: Integer and Long Real number: Single and Double Dates: Date True/False: Boolean Sentences: String

15 Aug Ask user values of x and y and print x+y Variables: x Single, y Single, z Single Example Start sub example1 Get value from user and store in x (Single) Get value from user and store in y (Single) Calculate x+y and store in z (Single) Print value of z End

15 Aug Ask user values of x and y, calculate x+y, ask user for integer value a and print (x+y)*a Variables: x Single, y Single, z Single, a Integer, result Single Example Get value from user and store in a (Integer) Print value of result End Calculate z*a and store in result (Single) Start sub example2 Get value from user and store in x (Single) Get value from user and store in y (Single) Calculate x+y and store in z (Single)

15 Aug Why should we rewrite a program that we have already written? We can give the subroutine a name, MySum, to be able to later reuse it. This reusable subroutine may have parameters, used to “communicate” with the other programs Reusing programs End Start subroutine MySum parameters: z (Single) Get value from user and store in x (Single) Get value from user and store in y (Single) Calculate x+y and store in z

15 Aug We “call” the subroutine MySum inside the main program and use its parameter Reusing programs Get value from user and store in a (Integer) Print value of result End Calculate z*a and store in result (Single) Start sub example2bis Call MySum(z) z(Single) End Start subroutine MySum parameters: z (Single) Get value from user and store in x (Single) Get value from user and store in y (Single) Calculate x+y and store in z

15 Aug We could use the subroutine also to get the values only and leave the calculation to the main program Reusing programs Get value from user and store in a (Integer) Print value of result End Calculate z*a and store in result (Single) Start sub example2ter Call GetXY(x,y) x(Single), y(Single) End Start subroutine GetXY parameters: x (Single), y (Single) Get value from user and store in x Get value from user and store in y Calculate x+y and store in z (Single)

15 Aug Homeworks Write a program which asks for a an amount of money, an interest rate and a number of years and prints the compound interest Rewrite the previous program using a separate subroutine GetData to get the data. Rewrite the previous program using also a separate subroutine PrintInterest to print the compound interest. Rewrite the previous program using a sub called main which does nothing else but calling subroutines GetData, CalculateInterest, PrintInterest, which do all the job. Write a program which asks for a an amount of money, an interest rate and two dates StartDate and EndDate. Using the expression NumberOfYears = DateDiff( “yyyy”, StartDate, EndDate ) to get the difference in years, re-use the previous subroutines CalculateInterest and PrintInterest to print the compound interest.

15 Aug IF-THEN-ELSE condition We want to branch the flow according to the value of a variable If (condition) Then (operations if true) Else (operations if false) End If

15 Aug Start with already values for x (Single) and y (Single). If x<y, print y-x, else print sentence “sorry” Variables: x Single, y Single, diff Single, sentence String Example Start with x (Single), y (Single) Print value of diff Calculate y-x and store in diff (Single) Put “sorry” in sentence (String) Print value of sentence End true false x < y

15 Aug Ask integer value. If it is positive, print “positive”, if it is not positive, ask for a real value and print it Variables: x Integer, y Single, sentence String Example Start Print value of y Put “positive” in sentence (String) Print value of sentence End true x > 0 false Get value from user and store in x (Integer) Get value from user and store in y (Single)

15 Aug Build sub example5 which asks for an integer value. If it is positive, it prints “positive”. If it is negative, it asks for a real value and prints it. If it is zero it does nothing. Variables: x Integer, y Single, sentence String Example Start Put “positive” in sentence (String) Print value of sentence End Print value of y true x > 0 false Get value from user and store in x (Integer) Get value from user and store in y (Single) true false x < 0

15 Aug Suppose there are two taxation systems, A and B. Build sub CalculateTax with flowchart which asks for the chosen taxation system and for the income and then prints the tax according to the rule: Class exercise SystemIncome levelTax A< >= % of income B< >= % of income

15 Aug Solution of class exercise Start sub CalculateTax tax (Double) End Print value of tax false system = “A” true Get value from user and store in system (String) true false income < Get value from user and store in income (Long) tax=3000tax=income*0.15 true false income < tax=9000tax=income*0.2 Use operator & to concatenate strings: ”result is ” & tax

15 Aug In order to help subroutine CalculateTax, use a subroutine DoCalc which needs income, income level, fixed tax, tax percentage and calculates the tax. Improvement

15 Aug Solution of improvement Start sub CalculateTax tax (Double) End Print value of tax false system = “A” true Get value from user and store in system (String) Get value from user and store in income (Long) End Start subroutine DoCalc parameters: income (Long), incomeLevel (Long), fixedTax (Long), taxPercentage (Single), tax (Double) tax=fixedTax tax=income*taxPercentage true false income < incomeLevel Call DoCalc(income, 20000,3000,0.15,tax) Call DoCalc(income, 50000,9000,0.2,tax)

15 Aug Whenever a subroutine 1.does not interact with the user 2.gets its input from the parameters 3.returns only one variable as output it is much more efficient to use a function instead of a subroutine Function calcTax2( … parameters … ) as Single … do the calculations here and put the result in a variable with the same name as the function … End Function Function

15 Aug Function Start sub CalculateTax tax (Double) End Print value of tax false system = “A” true Get value from user and store in system (String) Get value from user and store in income (Long) End returning calcTax Start function calcTax (Double) parameters: income (Long), incomeLevel (Long), fixedTax (Long), taxPercentage (Single) calcTax=fixedTax calcTax=income*taxPercentage true false income < incomeLevel tax=calcTax(income, 20000,3000,0.15) tax=calcTax(income, 50000,9000,0.2)

Print value of calcTax(income, 20000,3000,0.15) 15 Aug Functions are much more versatile and can be used directly in calculations and other functions or commands Usage of functions Start sub CalculateTax tax (Double) Print value of calcTax(income, 50000,9000,0.2) false system = “A” true Get value from user and store in system (String) Get value from user and store in income (Long) End

15 Aug Homeworks Write a program with flowchart which asks for a an amount of money, an interest rate and two dates StartDate and EndDate. Using a function to calculate the compound interest and a subroutine to get the data, print the compound interest. Write function TaxDeduction (flowchart is too long) which gets as input children, income and age and returns the Italian tax deduction according to: Children Age of youngest child Deduction 1 below 3 years900 · (95,000 – income) / 95,000 3 years and more800 · (95,000 – income) / 95,000 2 below 3 years900 · (110,000 – income) / 110,000 3 years and more800 · (110,000 – income) / 110,000 3 below 3 years900 · (125,000 – income) / 125,000 3 years and more800 · (125,000 – income) / 125,000 4 below 3 years1,100 · (140,000 – income) / 140,000 3 years and more1,000 · (140,000 – income) / 140,000 more than 4Same formulas as above but 140,000 is increased by 15,000 for every child after the fourth. Important: when the deduction is negative, it becomes 0.

15 Aug Write the squares of the numbers from 1 to 20 Example Start Set n (Integer) to 1 Print value of y Calculate n*n and store value in y (Long) Increment n by 1 Print value of y Calculate n*n and store value in y Increment n by 1 End

15 Aug FOR-NEXT loop We want to repeat the same procedure in a similar way several times FOR : SET UP A COUNTER (operations) NEXT : INCREMENT AND GO BACK To go out of the loop before its end: EXIT FOR

15 Aug Write the squares of the numbers from 1 to 20 Variables: n Integer, y Long Example6 Start Set n (Integer) to 1 and loop Print value of y End Calculate n*n and store value in y (Long) Increment n by 1 and loop until n does not exceed 20

15 Aug Write the square root of the numbers from 3126 to 1087 going backwards with steps of 31 Variables: n Integer, y Long Example7 Start Set n (Integer) to 3126 and loop Print value of y End Calculate sqr(n) and store value in y (Single) Increment n by -31 and loop until n does not go below 1087

15 Aug Write the square root of the numbers from 3126 to 1087 going backwards with steps of 31, asking the user at each step whether he wants the program to end. Example7bis Start Set n (Integer) to 3126 and loop Print value of y End Calculate sqr(n) and store value in y (Single) Increment n by -31 and loop until n does not go below 1087 truefalse goon =“yes” Get value from user and store in goon goon (String) Exit For

15 Aug Homework Write function isEven with flowchart, which wants an integer as input and returns a Boolean (a variable with value True or False, without quotations!). To detect whether a number is even, use as condition Int(number/2)=number/2. Write a program with flowchart which asks the user for a positive integer and computes the following sequence for 20 times: if the number is even, halve it; if it's odd, multiply by 3 and add 1. Repeat this process until 20 times have been reached or until the value is 1, printing out each value. Finally print out how many of these operations have been performed. Typical output might be: initial value is 9; next values are: 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1; number of steps 19

15 Aug Using functions A function may be used: by a subroutine (or by another function), via direct usage such as variable=functionName(parameters), where the subroutine is responsible for providing the parameters inside an Excel sheet, exactly like any other Excel function, where parameters are written directly or indicated as cell reference, such as =functionName(D7;E5;27;0;A1) Not run directly via Run button, since there is no way to pass parameters and no way to gather the function’s returned output

15 Aug Reading data from Excel sheet To access Excel sheet we use Range(“E2:H9”).Cells(3,2) which corresponds to cell F4, since (3,2) are the row and column of the range! Therefore E2 is (1,1), F2 is (1,2), F3 is (2,2) and F4 is (3,2). Range(“E2:H9”).Count which tells us the number of cells in the range (in this case 32)

15 Aug Example Write program Multiplic which reads number in cell D5, multiplies it by the number in cell D6 and prints the result. Compact it using a single instruction. Start End a (Single) a= Range(“D5”).Cells(1,1) Print value of a*b a = Range(“D1:D20”).Cells(5,1) b = Range(“D5:D6”).Cells(2,1) b (Single) b= Range(“D6”).Cells(1,1)

15 Aug Example Write program FixCell which asks the user for a cell reference and a real number and puts that number in that cell. Start End get a string from user and store it in cellReference (String) Range(cellReference).Cells(1,1)=value get a single from user and store it in value (Single)

15 Aug Array We want to store many values of the same type ARRAY It always needs to be prepared It is accessed directly indicating the index

15 Aug Ask the user 20 real numbers and store them into an array. Ask the user which value he wants to be printed and print it. Variables: x Array of Single, j Integer, n Integer Example11 Start Print value in n-th position of x Get value from user and store in n (Integer) End Set j (Integer) to 1 and loop Prepare an array x containing 20 single Get value from user and store in j-th position of x Increment j by 1 and loop until j exceeds 20

15 Aug Ask the user 20 real values. When you have all of them, calculate their sum. Then print it. Variables: x Array of Single, j Integer, sum Single Example11bis Start Print value of sum End Set j (Integer) to 1 and loop Prepare an array x containing 20 single Get value from user and store in j-th position of x Increment j by 1 and loop until j exceeds 20 sum (Single) sum = 0 j=1 and loop Increment j by 1 and loop until j exceeds 20 sum = sum + x (at j-th position)

15 Aug Improve the previous program using only one loop and telling each time which number the user is entering (4 th, 5 th, …) Improve it further more using 1 st, 2 nd, 3 rd instead of 1 th, 2 th, 3 th and do not use an array! Example11ter

15 Aug Example15 Read numbers in range D3:D13 and put them in array x with indexes 1 to 11. Then print the fifth element of the array Start End Set j (Integer) to 1 and loop Increment j by 1 and loop until j exceeds 11 x array of Single 1 To 11 x(j)= Range(“D3:D13).Cells(j,1) Print value of x(5) For j=3 To 13 x(j–2)=Range(“D1:D13”).Cells(j,1) For j=1 To 11 x(j)=Range(“D1:D13”).Cells(j+2,1)

15 Aug Get 20 values from D1:D20 and put them into an array. When you have all of them, ask the user for a bound. Then print how many of the 20 values exceed that bound. Example12 Start Print value of count End Set j (Integer) to 1 and loop Prepare an array x containing 20 single x(j)=Range(“D1:D20”).Cells(j,1) Increment j by 1 and loop until j exceeds 20 count (Integer) count= 0 j=1 and loop Increment j by 1 and loop until j exceeds 20 count = count+1 Get value from user and store in bound (Single) truefalse x(j) > bound

15 Aug Whenever we are not sure of from where to where the array index goes, we can use functions LBound(x) and UBound(x) which automatically take the value of the first and the last index of the array x Rewrite the previous program using LBound(x) and UBound(x) instead of 1 and 20 LBound and UBound

15 Aug Build a function countLargerThanLimit which accepts as input an array of singles and a limit and returns how many elements of the array are larger than the limit In this function you must use LBound and UBound because the function cannot know a priori the array bounds Example12ter

15 Aug Ask the user 20 real numbers. When you have all of them, calculate the average of the positive ones. Then print it. Hints First build a program which simply calculates the average Use count (Integer) variable to count how many are positive Start setting count=0 (exactly as sum is set equal to 0) Use IF-THEN-ELSE condition to check whether each number is positive (and therefore should be summed and counted) Example13

15 Aug Solution Start Print value of average End Set j (Integer) to 1 and loop Prepare an array x containing 20 single Get value from user and store in j-th position of x Increment j by 1 and loop until j exceeds 20 sum (Single) sum = 0 j=1 and loop Increment j by 1 and loop until j exceeds 20 sum = sum + x(j) average (Single) average = sum / count count (Integer) count = 0 count = count + 1 true x(j)>0 false

15 Aug What happens when all 20 values are negative? The computer crashes since a division by zero was found! We need to check that count be positive before dividing! Problem of the solution

15 Aug Better solution Start Print value of average End Set j (Integer) to 1 and loop Prepare an array x containing 20 single Get value from user and store in j-th position of x Increment j by 1 and loop until j exceeds 20 sum (Single) sum = 0 j=1 and loop Increment j by 1 and loop until j exceeds 20 sum = sum + x(j) average (Single) average = sum / count count (Integer) count = 0 count = count + 1 true x(j)>0 false true count>0 false Print value of sentence sentence (String) sentence = “sorry no positive”

15 Aug Build a function which receives d (array of 20 Date), m (Single) and r (array of 20 Single). For each d and r, if d is in the past and r is positive, calculate the interest from d to now, using m as money amount and the corresponding r as interest rate. Otherwise, do not consider this data. Return the average of the calculated interests. Hints You can use And operator (like in Access) To get current date, there is Now() function Write also a program which reads the data from columns G, H, I of Excel sheet and tests the function. Homework (example 14)

15 Aug Solution sum (Single) sum = 0 Start with d (array of 20 Date), m (Single), r (array of 20 Single) count (Int) count = 0 End returning average Set j (Integer) to 1 and loop Increment j by 1 and loop until j exceeds 20 false true d(j)<Now() And r(j)>0 count = count +1interest (Single) interest = m * ( 1+r(j) ) (Now – d(j)) / 365 – m sum = sum + interest Starting variables: d (array of 20 Date) m (Single) r (array of 20 Single) Used variables: interest (Single) count (Integer) sum (Single) average (Single) average = sum / count

15 Aug Homework Build function MaxOfArray which receives an array of singles and returns the maximum Hint: try to think at how would you do this task manually step by step and then replicate it on a program Build a subroutine to test the function, using the data in column D

15 Aug Solution Start function MaxOfArray Parameters: x array of Single End returning maxCandidate Set j (Integer) to second index of array and loop maxCandidate (Single) maxCandidate=first element of array Increment j by 1 and loop until j exceeds the last index of the array maxCandidate = x(j) true x(j)> maxCandidate false

15 Aug WHILE-WEND loop We want to repeat the same procedure in the same way until something happens WHILE : (condition) (operations) WEND : GO BACK

15 Aug Ask the user a real value. If it is negative, print “bye” and stop. If it is positive or zero, tell the user its square root and ask another. Go on over and over. Variables: y Single, squareroot Single, sentence String Example16 StartEnd While y >=0 Print value of squareroot go back Get value from user and store in y (Single) Calculate sqr(y) and store in squareroot (Single) Get value from user and store in y Print value of sentence sentence (String) sentence = “bye”

15 Aug Do not use WHILE- WEND loop but use IF instead. You need to “jump” to another place in the program and it is not possible (for the moment) Variables: y Single, squareroot Single, sentence String Equivalent example StartEnd Print value of squareroot Get value from user and store in y (Single) Calculate sqr(y) and store in squareroot (Single) Get value from user and store in y true y >= 0 false Print value of sentence sentence (String) sentence = “bye”

15 Aug Build a function which receives x (array of Single). It goes through each value of x calculating the sum of the values, stopping when a zero value is found. Then it returns the sum. Hints The loop can end for two reasons: a zero value is found or all 30 values have been examined You can use the FOR-NEXT loop, but in this case you must add a condition which “jumps” to the end of the program when a zero is found You can instead use the WHILE-WEND loop, but in this case you must add a manual counter to go through x which takes care of ending when it reaches 30 Build a sub which takes data from column D to test the function Homework (example17)

15 Aug Solutions End returning sum sum (Single) sum = 0 Start with x (Array of 30 Single) Set j (Integer) to first index and loop Increment j by 1 and loop until j exceeds last index true x(j) <> 0 false sum = sum + x(j) End returning sum sum (Single) sum = 0 Start with x (Array of 30 Single) sum = sum + x(j) Do only if x(j)<>0 and j<=last index go back j (Integer) j = first index j = j + 1

15 Aug Build a program which reads an array of singles (for example D1:D22) and reprints them sorted from smallest to largest Hints First think at how you would do this task step by step manually Then rethink carefully at each step of the manual procedure Then, according to the algorithm you have invented, it might be useful either to build a separate array to put the data or to build a subroutine which accepts an array and two indexes and switches the position of the elements in the array Extremely difficult homework