University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 1 Lecture Outline Mathematical Expressions String Concatenation Built-in.

Slides:



Advertisements
Similar presentations
ISOM3230 Business Applications Programming
Advertisements

COMPUTER PROGRAMMING I Essential Standard 5.02 Understand Breakpoint, Watch Window, and Try And Catch to Find Errors.
1.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Tutorial 12: Enhancing Excel with Visual Basic for Applications
Val Function A Function performs an action and returns a value The expression to operate upon, known as the argument, (or multiple arguments), must be.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Introduction to Computing Dr. Nadeem A Khan. Lecture 4.
Input Validation Check the values entered into a text box before beginning any calculations Validation is a form of ‘self-protection’, rejecting bad data.
CSC110 Fall Chapter 5: Decision Visual Basic.NET.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 6 Enhancing the Inventory Application Introducing Variables, Memory Concepts and.
Variables and Constants
Microsoft Visual Basic 2008: Reloaded Fourth Edition
University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-3 1 Lecture Outline Variable Scope Calling another subprogram Programming.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #4: Working with Variables and User Interfaces IE 212: Computational Methods for Industrial Engineering.
Intrinsic Functions Pre-coded Functions Used to improve developer productivity Broad Range of Activities Math calculations Time/Date functions String.
1 Chapter 9 Writing, Testing, and Debugging Access Applications.
Enhancing User Interaction Through Programming
Chapter 4 The If…Then Statement
University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA 1 Lecture Outline Record macro and examine VBA code VBA Editor (IDE)
Chapter 4 P 1 Decisions and Conditions Control statements - seqeuncing - selection - repetition (picture later) - abstraction (procedure calls)
Computer Science Selection Structures.
Microsoft Visual Basic 2005 BASICS Lesson 4 Mathematical Operators.
Chapter 4: The Selection Process in Visual Basic.
Visual Basic.NET BASICS Lesson 4 Mathematical Operators.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 2 Input,
Input, Output, and Processing
Visual Basic for Applications Macro Programming For Microsoft Office.
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
Visual Basic Programming
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
Input Validation Check the values entered into a text box before beginning any calculations Validation is a form of ‘self-protection’, rejecting bad data.
Introduction to Visual Basic Programming. Introduction Simple Program: Printing a Line of Text Another Simple Program: Adding Integers Memory Concepts.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
Variables & Function Calls. Overview u Variables  Programmer Defined & Intrinsic  Data Types  Calculation issues u Using Functions  The val() function.
‘Tirgul’ # 2 Enterprise Development Using Visual Basic 6.0 Autumn 2002 Tirgul #2.
1 CS105 Discussion 5 – Variables and If Announcements MP 1 due on Monday Midterm 1 on Tuesday If you need a conflict, request it NOW!!
1 Scripting Languages VBScript - Recognized mainly by Internet Explorer only - Netscape does have a plug-in JavaScript - Recognized by Internet Explorer.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Three Memory Locations and Calculations.
Chapter 4 Variables and constants. 4.1 Variables -Use of variables is good programming style -easier to modify -easier for a programmer to understand.
Chapter 3 Control Structures. The If…Then Statement The If…Then statement is a Decision statement = that executes a set of statements when a condition.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
1 Chapter 3 – Examples The examples from chapter 3, combining the data types, variables, expressions, assignments, functions and methods with Windows controls.
PROGRAM ESSENTIALS. TOKENS  SMALLEST UNITS OF A PROGRAM LANGUAGE  Special Symbols  Mathematical Operators  Punctuation  Word Symbols  Key Words.
Chapter 4 Getting Started with VBA. Subroutines Subroutine is the logical section of code that performs a particular task. Subroutine is also called a.
CECS 5020 Computers in Education Visual Basic Variables and Constants.
Controlling Program Flow with Looping Structures
Visual Basic.net Functions. Function (Defined) A procedure that returns a value when called.
Controlling Program Flow with Decision Structures.
Tutorial 4: The Selection Structure 1 Tutorial 4 The Selection Structure.
VBA Programming Functions and Decisions. If-Then-Else Structure used to consider alternatives If then --or-- If then Else End If.
Knowledge Base. Defining a Variable Dim statement Dim intXX As Integer Public in a Module Public dblNN As Double.
Creation of Variables with Numeric, alphanumeric, date, picture, memo data types Constant - A quantity that does not change during the execution of a program.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
Making Interactive Programs with Visual Basic .NET
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are used in programs so that values can be represented with.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration statement. For example: Dim.
Chapter 6 Controlling Program Flow with Looping Structures.
Slide 1 Chapter 4 The If…Then Statement  Conditional control structure, also called a decision structure  Executes a set of statements when a condition.
TUTORIAL 4 Visual Basic 6.0 Mr. Crone. Pseudocode Pseudocode is written language that is part-code part- English and helps a programmer to plan the layout.
A variable is a name for a value stored in memory.
Completing the Problem-Solving Process
The Selection Structure
Chapter 3: Introduction to Problem Solving and Control Statements
Data Types List Box Combo Box Checkbox Option Box Visual Basic 6.0
Presentation transcript:

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 1 Lecture Outline Mathematical Expressions String Concatenation Built-in Functions Planning for Programming Debugging Decisions (Branching/Selection) If – Then – Else ElseIf Select Case

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 2 Mathematical Expressions iAns = 3 + 2*(iNum/4) precedence order ( )Brackets ^Exponentiation -Negation / *Division and Multiplication in order of occurrence \Integer division ModDivision remainder (modulus) + -Addition and Subtraction in order of occurrence

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 3 Mathematical Expressions vAns becomes vAns = 5 ^ 2 25 vAns = 8 / 2 4 vAns = 81 / vAns = 9 \ 6 1 vAns = 9 Mod 6 3 vAns = 3 \ 5 * 2 0 vAns = 4 * 5 Mod 2 ^ 3 4 vAns = (1 + 2) ^ (3 \ 4) 1 vAns = ^ 2 \ 4 3 vAns = 10 * (4 + 2) / 3 20 vAns = * 2 / 3 ^ 2 3

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 4 String Concatenation Dim sFullName, sName As String Concatenation sFullName = “Homer” & “Simpson” sFullName = “Homer” & “ “ & “Simpson” Concatenation and Replacement sName = InputBox(“Enter your name:”) sName = “Name: ” & sName Output on two lines sFullName = “Homer” & vbNewLine & “Simpson”

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 5 String Functions sText = “Hi, Snipe” Len(string) returns integer iVal = Len(sText) 9 Left(string, length) returns string sVal = Left(sText, 5) “Hi, S” Right(string, length) returns string sVal = Right(sText, 2) “pe”

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 6 String Functions Assume: sText = “Hi, Snipe” Mid(string, start[, length]) returns string sVal = Mid(sText, 3, 4) “, Sn” sVal = Mid(sText, 3) “, Snipe” InStr(start, string1, string2) returns int iPos = InStr(1, sText, “,”) 3 iPos = InStr(1, sText, “b”) 0 (not found)

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 7 String Function Example sName = “Hunter, Andria” How would you extract “Andria”? find position of comma vCommAt = InStr(1, sName, “,”) use Mid starting 2 characters after comma vFirstName = Mid(sName, vCommAt+2) Alternate method – nest the function vFirstName = Mid(sName, Instr(1, sName, “,”)+2)

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 8 Type Conversion Functions Format(number, format) returns string Format( , “$###.00”) “$123.88” Format( , “0.0”) “123.9” Format( ,”Currency”) “$123.88” Val(string) returns number Val(“125 lbs”) 125 Val(“65”) 65 Str(number)returns string Str(365) “365”

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 9 Type Mismatch Errors When value assigned to variable does not match the variable’s declaration type Dim iNum As Integer iNum = 15 iNum = 21.6 rounds to integer iNum = “CSC A01F” type mismatch error iNum = “8.7” converts to numeric Dim sText As String sText = 12.9 converts to string

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 10 Planning for Programming 1. Observe process to be automated 2. Draw Flowchart 3. Write Pseudo Code 4. Edit Code with VBA Editor 5. Run and Test analysis design programming testing maintenance

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 11 Observe the Process State problem: Given cost of materials & labour, and knowing markup for overhead & profit, determine price to bid. Identify formula: Price = (Materials + Labour) * (1 + Overhead + Profit) Price = Cost + OH + Profit Identify Variables - entered by user  Material cost  Labour cost Identify Constants - set by programmer  Overhead percentage (85%)  Profit percentage (30%)

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 12 Observe the Process Having identified: Formula to Use Variables Constants Define specifically: Inputs – items the user will enter Outputs – form and media

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 13 Flow Charts Schematic drawing of the process Decisions Start or Stop Process steps Data Input/Output Predefined Process use standard symbols flow from top to bottom connect with arrows

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 14 Problem: Get Coffee! Any task can be flow- charted Each step could have its own chart Decision introduces a branch (selection) Start Decide you need a cup of coffee Get cup Go to coffee pot Is pot empty? Fill cup No End Yes Make coffee

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 15 Problem: Cost Model Start Get user inputs  Material  Labour Determine total cost Determine bid price Output results Quit Start Get: Labour cost Material cost Determine: Total cost Bid Price Show Bid Price Quit

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 16 Pseudo Code Display message showing [vPrice] [vCost] = [vLabour] + [vMaterial] [vPrice] = [vCost]*(1+[dOH]+[dPROFIT]) Ask user for labour cost [vLabour] and material cost [vMaterial] Write steps, formulas needed Pseudo Code often ends up as comments in the VBA code Start Get: Labour cost Material cost Determine: Total cost Bid Price Show Bid Price Quit

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 17 Sub BidPrice() Dim vLabour, vMaterial, vCost, vPrice Const dOH = 0.85 Const dPROFIT = 0.3 'Ask user for labour cost and material cost vLabour = InputBox("Enter the labour cost:") vMaterial = InputBox("Enter the cost of materials:") 'Total cost is labour plus materials vCost = Val(vLabour) + Val(vMaterial) 'Price is total cost, with overhead and profit markup vPrice = vCost * (1 + dOH + dPROFIT) 'Display message showing bid price MsgBox "Bid price is " & Format(vPrice, “Currency”) End Sub Write VBA Code

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 18 Run and Test Run the program Test with different inputs  confirm the logic is correct  confirm there are no bugs The program should not crash!!

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 19 Debugging Debug Toolbar Breakpoints Observed Values Watches Step Into Step Over

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 20 Debugging Step Into: process one line Debug Toolbar Breakpoint Yellow: next line to process Observed value: cursor on object Watch an expression

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 21 Conditional Expression Evaluates to true or false used to make a decision Formed by using a comparison operator: = > = <= true iValue <= iCount ? “apple” < “cat” true Range(“B2”) = Range(“B3”) ?

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 22 If-Then Execute code only if condition is true If condition Then Actions if condition is true End If dPrice = InputBox(“Enter Price:”) If dPrice > 1000 Then MsgBox “Too expensive!” End If

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 23 If-Then Flow chart branches forward Dim sName As String sName = Inputbox(“Name?”) If sName = “” Then sName = Inputbox(“Name?”) End If Range(“B3”) = sName Start Get user name Is name empty? Write name to cell B3 End Get user name Yes No

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 24 If-Then-Else Selects one of two choices If condition Then Actions if condition is true Else Actions if condition is false End If

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 25 If-Then-Else Flow chart takes one of two paths If Range(“B3”) < 0 Then Range(“B3”).Font.ColorIndex = 3 Else Range(“B3”).Font.ColorIndex = 1 End If Is value negative? Set text color to black Yes No Set text color to red

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 26 If-Then-Else Example Determine which message to display Dim sName, sOut As String sName = InputBox (“What’s your name?”) If sName = “” Then sOut = “You didn’t enter a name!” Else sOut = “Welcome, ” & sName & “.” End if MsgBox sOut

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 27 MsgBox(prompt, buttons, title)  returns int vAns = MsgBox(“It’s raining.”, vbOKOnly, “Raining”) vAns = MsgBox(“Is it raining?”, vbYesNo, “Raining”) vAns = MsgBox(“I said RAIN!”, vbOKCancel, “Raining”) What is returned? vbOK, vbYes, vbNo, vbCancel MsgBox Function

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 28 MsgBox If-Then Example Examine value returned by MsgBox and take an appropriate action iAns = MsgBox(“Is it raining?”, vbYesNo) If iAns = vbYes Then sOut = “Help, it’s raining!” Else sOut = “Yippee, it’s dry!” End if MsgBox sOut

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 29 Select only one of a number of options Stops when first true condition encountered iQuantity = InputBox(“Enter Quantity:“) If iQuantity <= 25 Then dDiscount = 0.10 ElseIf iQuantity <= 50 Then dDiscount = 0.15 ElseIf iQuantity <= 75 Then dDiscount = 0.20 Else dDiscount = 0.25 End If MsgBox “Discount is “ & Format(dDiscount, ”Percent”) If–Then-ElseIf-Else

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 30 Multiple Choice Get Colour Is Colour Green ? Is Colour Red ? No Is Colour Blue ? No Set text color to Blue Yes Set text color to Green Set text color to Red Yes

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 31 Multiple Choice Use ElseIf to select sMyColour = InputBox (“Colour?”) If sMyColour = “Green” Then Range(“B3”).Font.Color = vbGreen ElseIf sMyColour = “Red” Then Range(“B3”).Font.Color = vbRed ElseIf sMyColour = “Blue” Then Range(“B3”).Font.Color = vbBlue End If

University of Toronto at Scarborough © Andria Hunter, Kersti Wain-Bantin CSCA01 VBA-2 32 Multiple Choice Or use Select Case sMyColour = InputBox (“Colour?”) Select Case sMyColour Case “Green” Range(“B3”).Font.Color = vbGreen Case “Red” Range(“B3”).Font.Color = vbRed Case “Blue” Range(“B3”).Font.Color = vbBlue End Select